helm-schema-ir 0.0.4

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
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
use std::collections::BTreeSet;

use helm_schema_ast::{Literal, TemplateExpr};

use crate::abstract_value::AbstractValue;
use crate::expr_eval::eval_expr;
use crate::{Guard, GuardValue};
use helm_schema_ast::type_is_schema_type;
use helm_schema_core::Predicate;

use super::ValuePathContext;

fn is_files_get_function(function: &str) -> bool {
    function == "Files.Get" || function.ends_with(".Files.Get")
}

/// Dispatch-arm headers may themselves compare helper outputs; one level
/// covers the chart shapes seen so far, and the cap keeps mutually
/// recursive helpers from looping the decoder.
const MAX_HELPER_DISPATCH_DEPTH: u8 = 2;

thread_local! {
    static HELPER_DISPATCH_DEPTH: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
}

/// An `include`/`template` call whose context argument carries the root
/// (`.` or `$`), so the callee's `.Values.*` conditions keep their paths.
fn helper_root_call(expr: &TemplateExpr) -> Option<&str> {
    let TemplateExpr::Call { function, args } = expr.deparen() else {
        return None;
    };
    let name = crate::expr_eval::literal_helper_call_callee(function, args)?;
    let [_, context] = args.as_slice() else {
        return None;
    };
    let root_context = match context.deparen() {
        TemplateExpr::Field(path) => path.is_empty(),
        TemplateExpr::Variable(variable) => variable.is_empty(),
        _ => false,
    };
    root_context.then_some(name)
}

fn literal_string(expr: &TemplateExpr) -> Option<&str> {
    match expr.deparen() {
        TemplateExpr::Literal(Literal::String(text) | Literal::RawString(text)) => Some(text),
        _ => None,
    }
}

/// The typed guard value of a plain scalar literal. Floats abstain: their
/// file-vs-`--set` numeric channels compare differently, so an equality
/// target would overstate what the analysis knows.
fn literal_guard_value(expr: &TemplateExpr) -> Option<GuardValue> {
    match expr.deparen() {
        TemplateExpr::Literal(Literal::String(value) | Literal::RawString(value)) => {
            Some(GuardValue::string(value.clone()))
        }
        TemplateExpr::Literal(Literal::Bool(value)) => Some(GuardValue::Bool(*value)),
        TemplateExpr::Literal(Literal::Int(value)) => Some(GuardValue::Int(*value)),
        _ => None,
    }
}

fn literal_membership_string(expr: &TemplateExpr) -> Option<String> {
    if let Some(value) = literal_string(expr) {
        return Some(value.to_string());
    }
    let TemplateExpr::Call { function, args } = expr.deparen() else {
        return None;
    };
    let [arg] = args.as_slice() else {
        return None;
    };
    let value = literal_string(arg)?;
    match function.as_str() {
        "quote" if value.is_empty() => Some("\"\"".to_string()),
        "squote" if value.is_empty() => Some("''".to_string()),
        _ => None,
    }
}

/// Split a printf format around a single `%s` verb; any other verb (or a
/// second `%s`) makes the produced name undecodable.
fn single_string_verb_split(format: &str) -> Option<(&str, &str)> {
    let index = format.find("%s")?;
    let (prefix, rest) = format.split_at(index);
    let suffix = &rest[2..];
    (!prefix.contains('%') && !suffix.contains('%')).then_some((prefix, suffix))
}

impl ValuePathContext<'_> {
    /// Whether `condition_predicate_expr` represents this expression
    /// EXACTLY, with no truthy fallback and no silently dropped conjunct.
    /// Rows tolerate approximate (wider) conditions; fail-branch NEGATION
    /// does not, so it consults this before trusting a captured stack.
    pub(crate) fn condition_lowering_is_faithful(&self, expr: &TemplateExpr) -> bool {
        match expr.deparen() {
            TemplateExpr::VariableDefinition { value, .. }
            | TemplateExpr::Assignment { value, .. } => self.condition_lowering_is_faithful(value),
            TemplateExpr::Field(_) | TemplateExpr::Selector { .. } => {
                if self.root_field_truthy_predicate(expr).is_some() {
                    return true;
                }
                !self.paths_for_expr(expr).is_empty()
            }
            TemplateExpr::Literal(_) => true,
            // A local bound to DERIVED TEXT (`$message := join "\n"
            // $messages`) is falsy when the derivation produced nothing,
            // not when its input identities are falsy: a truthy stand-in
            // over the flowing paths would let negation fire on states the
            // branch never reaches (bitnami `validateValues` aggregators).
            TemplateExpr::Variable(name) => {
                if let Some(predicate) = self.template_truthy_reductions.get(name).or_else(|| {
                    self.template_truthy_reductions
                        .get(name.trim_start_matches('$'))
                }) {
                    return !matches!(predicate, Predicate::False);
                }
                if self.get_binding_truthy_predicate(name).is_some() {
                    return true;
                }
                // Layered merges decode through their own disjunction lane;
                // the all-paths conjunction below is not faithful for them.
                if let Some(AbstractValue::MergedLayers(layers)) =
                    eval_expr(expr, &self.expression_eval_env()).value
                {
                    return merged_layers_truthy_predicate(&layers).is_some();
                }
                let paths = self.paths_for_expr(expr);
                if paths.is_empty() {
                    return false;
                }
                let metas = self
                    .template_output_meta
                    .get(name)
                    .or_else(|| self.template_output_meta.get(name.trim_start_matches('$')));
                !paths.iter().any(|path| {
                    metas
                        .and_then(|metas| metas.get(path))
                        .is_some_and(|meta| meta.derived_text || meta.shape_erased)
                })
            }
            TemplateExpr::Call { function, args } => match function.as_str() {
                "and" | "or" => args
                    .iter()
                    .all(|arg| self.condition_lowering_is_faithful(arg)),
                "list" | "tuple" | "dict" => true,
                "not" => {
                    args.first()
                        .is_some_and(|arg| self.condition_lowering_is_faithful(arg))
                        && args.len() == 1
                        && self.not_predicate(args).is_some()
                }
                "eq" => self.value_comparison_predicate(args, false).is_some(),
                "ne" => self.value_comparison_predicate(args, true).is_some(),
                "semverCompare" => self.semver_capabilities_predicate(args).is_some(),
                "gt" | "lt" | "ge" | "le" => self.positive_len_predicate(function, args).is_some(),
                "typeIs" | "kindIs" => self.type_is_predicate(args).is_some(),
                "hasKey" => self.has_key_predicate(args).is_some(),
                "hasPrefix" => {
                    self.range_key_prefix_predicate(args).is_some()
                        || self.string_affix_predicate(args, false).is_some()
                }
                "hasSuffix" => self.string_affix_predicate(args, true).is_some(),
                "contains" => self.contains_predicate(args).is_some(),
                "has" => self.helper_literal_membership_predicate(args).is_some(),
                "empty" => self.empty_predicate(args).is_some(),
                "coalesce" => self.coalesce_truthy_predicate(args).is_some(),
                "default" => self.default_truthy_predicate(args).is_some(),
                "merge" | "mustMerge" | "mergeOverwrite" | "mustMergeOverwrite" => {
                    self.merge_truthy_predicate(args).is_some()
                }
                "dig" => self.dig_truthy_predicate(args).is_some(),
                "toString" => matches!(args.as_slice(), [arg]
                    if self.tostring_truthy_predicate(arg).is_some()),
                "regexMatch" | "mustRegexMatch" => self.regex_match_predicate(args).is_some(),
                "include" => self.include_truthy_predicate(expr).is_some(),
                function if is_files_get_function(function) => {
                    self.files_get_printf_predicate(args).is_some()
                }
                _ => false,
            },
            TemplateExpr::Pipeline(stages) => {
                self.default_pipeline_truthy_predicate(stages).is_some()
                    || self.tostring_pipeline_truthy_predicate(stages).is_some()
                    || self.pipeline_membership_predicate(stages).is_some()
            }
            _ => false,
        }
    }

    pub(crate) fn condition_predicate_expr(&self, expr: &TemplateExpr) -> Predicate {
        if let TemplateExpr::VariableDefinition { value, .. }
        | TemplateExpr::Assignment { value, .. } = expr.deparen()
        {
            return self.condition_predicate_expr(value);
        }
        if let Some(predicate) = self.condition_predicate(expr) {
            return predicate;
        }
        if self.condition_has_unrepresentable_values_comparison_expr(expr) {
            return Predicate::True;
        }
        self.truthy_predicate(expr).unwrap_or(Predicate::True)
    }

    pub(crate) fn approximate_condition_predicate_expr(
        &self,
        expr: &TemplateExpr,
        marker: &str,
    ) -> Predicate {
        self.approximate_condition_parts(expr, marker, false)
    }

    /// One node of an approximately-lowered condition, decomposed as far as
    /// the Boolean structure allows.
    ///
    /// `and`/`or` decompose per argument so exact conjuncts survive beside
    /// undecodable siblings, recursing into nested connectives (cilium's
    /// `or (and (ge …) (le …)) (and (ge …) (le …))` cluster-id window):
    /// a fail-arm consumer can then strengthen the residue soundly (drop
    /// approximate disjuncts, or negate only the decodable conjuncts)
    /// instead of abstaining on one opaque blob. `not` distributes by
    /// De Morgan — each negated leaf either decodes exactly and negates,
    /// or carries the region-flipped comparison subset (cilium's
    /// `not (and (ge (int …) 0) (le (int …) 4294967295))` baseID domain).
    fn approximate_condition_parts(
        &self,
        expr: &TemplateExpr,
        marker: &str,
        negated: bool,
    ) -> Predicate {
        let TemplateExpr::Call { function, args } = expr.deparen() else {
            // A pipeline condition may still admit a positive sound
            // strengthening (cilium's transformed `… | semverCompare
            // "<0.9.0"` fail gate) even though the pipeline itself stays
            // approximate.
            if !negated {
                let subset = self.comparison_sound_subset(expr);
                if !subset.is_empty() {
                    return Predicate::approximate_with_sound_subset(
                        marker,
                        self.resolved_values_paths_from_expr(expr),
                        subset,
                    );
                }
            }
            let leaf = Predicate::approximate(marker, self.resolved_values_paths_from_expr(expr));
            // The stand-in covers the unknown condition in BOTH polarities:
            // an Approximate marker is never negated downstream, so the
            // negated leaf keeps the same abstention.
            return leaf;
        };
        match function.as_str() {
            // Under negation, De Morgan swaps the connective.
            "and" | "or" => {
                let parts: Vec<Predicate> = args
                    .iter()
                    .enumerate()
                    .map(|(index, arg)| {
                        if !negated && self.condition_lowering_is_faithful(arg) {
                            self.condition_predicate_expr(arg)
                        } else if negated
                            && self.condition_lowering_is_faithful(arg)
                            && let Some(exact) = self.condition_predicate(arg)
                        {
                            exact.negated()
                        } else {
                            self.approximate_condition_parts(
                                arg,
                                &format!("{marker}:{index}"),
                                negated,
                            )
                        }
                    })
                    .collect();
                if (function == "and") == negated {
                    predicate_any(parts)
                } else {
                    Predicate::all(parts)
                }
            }
            "not" if args.len() == 1 => {
                // The whole negated atom may decode as its own subset —
                // negated literal membership rides the full
                // `not (list … | has X)` shape — before De Morgan descends.
                if !negated {
                    let whole = self.comparison_sound_subset(expr);
                    if !whole.is_empty() {
                        return Predicate::approximate_with_sound_subset(
                            marker,
                            self.resolved_values_paths_from_expr(expr),
                            whole,
                        );
                    }
                }
                let Some(arg) = args.first() else {
                    return Predicate::approximate(marker, BTreeSet::new());
                };
                self.approximate_condition_parts(arg, &format!("{marker}:!"), !negated)
            }
            _ => {
                if let Some(predicate) = self.int_cast_region_disjunction(expr, marker, negated) {
                    return predicate;
                }
                Predicate::approximate_with_sound_subset(
                    marker,
                    self.resolved_values_paths_from_expr(expr),
                    if negated {
                        self.negated_comparison_sound_subset(expr)
                    } else {
                        self.comparison_sound_subset(expr)
                    },
                )
            }
        }
    }

    /// `ne (int X) L` (and the negated `eq`) certainly holds when the
    /// coercion certainly lands strictly below OR strictly above the
    /// literal, so the claim carries BOTH region arms as a disjunction of
    /// strengthened approximates instead of the raw-integer-only
    /// conjunction: each arm's `IntGt`/`IntLt` guard contributes its exact
    /// base-0 string preimage at encoding time (cilium rejects
    /// `cluster.id: "1"` under the default cluster name, and
    /// `maxConnectedClusters` spellings outside {255, 511}).
    fn int_cast_region_disjunction(
        &self,
        expr: &TemplateExpr,
        marker: &str,
        negated: bool,
    ) -> Option<Predicate> {
        let TemplateExpr::Call { function, args } = expr.deparen() else {
            return None;
        };
        match (function.as_str(), negated) {
            ("ne", false) | ("eq", true) => {}
            _ => return None,
        }
        let [left, right] = args.as_slice() else {
            return None;
        };
        let (cast_expr, literal) = match (left.deparen(), right.deparen()) {
            (cast, TemplateExpr::Literal(Literal::Int(literal)))
            | (TemplateExpr::Literal(Literal::Int(literal)), cast) => (cast, *literal),
            _ => return None,
        };
        let source = self.int_cast_operand(cast_expr)?;
        let paths = self.resolved_values_paths_from_expr(expr);
        // A literal `default` substitutes for every Helm-falsy input
        // BEFORE the comparison: when the fallback equals the literal, a
        // raw 0 and the empty string no longer satisfy `ne`, so both arms
        // exclude them (the other falsy spellings match no arm encoding).
        let default_collides = literal != 0 && source.default_int == Some(literal);
        let arm = |guard: Guard, tag: &str| {
            let mut guards = vec![guard];
            if default_collides {
                guards.push(Guard::NotEq {
                    path: source.path.clone(),
                    value: helm_schema_core::GuardValue::Int(0),
                });
                guards.push(Guard::NotEq {
                    path: source.path.clone(),
                    value: helm_schema_core::GuardValue::string(""),
                });
            }
            Predicate::approximate_with_sound_subset(
                format!("{marker}:{tag}"),
                paths.clone(),
                guards,
            )
        };
        Some(Predicate::Or(vec![
            arm(
                Guard::IntLt {
                    path: source.path.clone(),
                    bound: literal,
                },
                "lt",
            ),
            arm(
                Guard::IntGt {
                    path: source.path.clone(),
                    bound: literal,
                },
                "gt",
            ),
        ]))
    }

    pub(crate) fn with_condition_predicate_expr(&self, expr: &TemplateExpr) -> Predicate {
        Predicate::all(
            self.condition_predicate_expr(expr)
                .with_context_predicates(),
        )
    }

    fn condition_predicate(&self, expr: &TemplateExpr) -> Option<Predicate> {
        if let TemplateExpr::Pipeline(stages) = expr.deparen() {
            return self
                .default_pipeline_truthy_predicate(stages)
                .or_else(|| self.tostring_pipeline_truthy_predicate(stages))
                .or_else(|| self.pipeline_membership_predicate(stages));
        }
        let TemplateExpr::Call { function, args } = expr.deparen() else {
            return self.truthy_predicate(expr);
        };
        match function.as_str() {
            "and" => self.and_predicate(args),
            "list" | "tuple" | "dict" => Some(bool_predicate(!args.is_empty())),
            "not" => self.not_predicate(args),
            "empty" => self.empty_predicate(args),
            "hasKey" => self.has_key_predicate(args),
            "hasPrefix" => self
                .range_key_prefix_predicate(args)
                .or_else(|| self.string_affix_predicate(args, false)),
            "hasSuffix" => self.string_affix_predicate(args, true),
            "contains" => self.contains_predicate(args),
            "has" => self
                .helper_literal_membership_predicate(args)
                .or_else(|| self.truthy_predicate(expr)),
            "or" => self.or_predicate(args),
            "eq" => self.value_comparison_predicate(args, false),
            "ne" => self.value_comparison_predicate(args, true),
            "semverCompare" => self.semver_capabilities_predicate(args),
            "gt" | "lt" | "ge" | "le" => self.positive_len_predicate(function, args),
            "typeIs" | "kindIs" => self.type_is_predicate(args),
            "coalesce" => self.coalesce_truthy_predicate(args),
            "default" => self.default_truthy_predicate(args),
            "merge" | "mustMerge" | "mergeOverwrite" | "mustMergeOverwrite" => {
                self.merge_truthy_predicate(args)
            }
            "dig" => self
                .dig_truthy_predicate(args)
                .or_else(|| self.truthy_predicate(expr)),
            "toString" if args.len() == 1 => self
                .tostring_truthy_predicate(args.first()?)
                .or_else(|| self.truthy_predicate(expr)),
            "regexMatch" | "mustRegexMatch" => self.regex_match_predicate(args),
            "include" => self
                .include_truthy_predicate(expr)
                .or_else(|| self.truthy_predicate(expr)),
            function if is_files_get_function(function) => self
                .files_get_printf_predicate(args)
                .or_else(|| self.truthy_predicate(expr)),
            _ => self.truthy_predicate(expr),
        }
    }

    /// Truthiness of a total stringification (`toString X` /
    /// `X | toString`) tests the RENDERED text against the empty string,
    /// never the raw value's own Helm truthiness: `"false"`, `"0"`, and
    /// `"<nil>"` are all truthy strings (cilium's removed-option guards
    /// rely on exactly that to abort on explicitly-disabled options).
    ///
    /// Two subjects decode exactly:
    ///
    /// - a literal-key `dig` with an EMPTY-STRING literal default: a
    ///   missing chain renders the empty default (falsy), so the guard
    ///   holds exactly when the leaf is present with any value other than
    ///   the empty string — explicit null renders `"<nil>"`, which is
    ///   truthy;
    /// - a direct selector: an absent or null subject renders `"<nil>"`
    ///   (truthy), so only the raw empty string is falsy.
    fn tostring_truthy_predicate(&self, subject: &TemplateExpr) -> Option<Predicate> {
        if let TemplateExpr::Call { function, args } = subject.deparen()
            && function == "dig"
        {
            let (map, rest) = args.split_last()?;
            let (default, key_exprs) = rest.split_last()?;
            if key_exprs.is_empty() {
                return None;
            }
            let keys = key_exprs
                .iter()
                .map(literal_string)
                .collect::<Option<Vec<_>>>()?;
            // Only the empty-string default keeps "missing renders falsy"
            // exact: any other falsy literal (`false`, `0`) stringifies to
            // truthy text, flipping the absent case.
            if !literal_string(default)?.is_empty() {
                return None;
            }
            let AbstractValue::ValuesPath(base) = self.with_body_fragment_value_expr(map)? else {
                return None;
            };
            let (leaf_key, parent_keys) = keys.split_last()?;
            let parent = parent_keys.iter().fold(base, |path, key| {
                helm_schema_core::append_value_path(&path, key)
            });
            let path = helm_schema_core::append_value_path(&parent, leaf_key);
            // `HasKey` (not `¬Absent`): dig OBSERVES a present nil member,
            // which renders as truthy "<nil>".
            return Some(Predicate::all(vec![
                Predicate::from(Guard::HasKey {
                    path: parent,
                    key: (*leaf_key).to_string(),
                }),
                Predicate::from(Guard::NotEq {
                    path,
                    value: GuardValue::string(""),
                }),
            ]));
        }
        if matches!(
            subject.deparen(),
            TemplateExpr::Field(_) | TemplateExpr::Selector { .. }
        ) {
            let path = self.single_resolved_values_path_expr(subject)?;
            return Some(Predicate::from(Guard::NotEq {
                path,
                value: GuardValue::string(""),
            }));
        }
        None
    }

    /// The `X | toString` pipeline form of [`Self::tostring_truthy_predicate`].
    fn tostring_pipeline_truthy_predicate(&self, stages: &[TemplateExpr]) -> Option<Predicate> {
        let [primary, stage] = stages else {
            return None;
        };
        let TemplateExpr::Call { function, args } = stage.deparen() else {
            return None;
        };
        (function == "toString" && args.is_empty())
            .then(|| self.tostring_truthy_predicate(primary))
            .flatten()
    }

    /// `dig k1 … kn default subject` with literal keys, a FALSY literal
    /// default, and one values-backed map subject is truthy exactly when
    /// the dug path's value is truthy: a missing chain yields the falsy
    /// default, and a present chain yields the leaf value itself. Truthy
    /// or non-literal defaults abstain (absence would select a truthy
    /// fallback), as does a subject without a single map identity.
    fn dig_truthy_predicate(&self, args: &[TemplateExpr]) -> Option<Predicate> {
        let (subject, rest) = args.split_last()?;
        let (default, key_exprs) = rest.split_last()?;
        if key_exprs.is_empty() {
            return None;
        }
        let keys = key_exprs
            .iter()
            .map(literal_string)
            .collect::<Option<Vec<_>>>()?;
        let TemplateExpr::Literal(literal) = default.deparen() else {
            return None;
        };
        if literal_is_truthy(literal) {
            return None;
        }
        // The subject must be ONE values-backed map identity — the
        // whole-values root (`.Values` or `.Values.AsMap`) or a single
        // path. A choice of subjects would misstate the leaf condition.
        let AbstractValue::ValuesPath(base) = self.with_body_fragment_value_expr(subject)? else {
            return None;
        };
        let path = keys.iter().fold(base, |path, key| {
            helm_schema_core::append_value_path(&path, key)
        });
        Some(Predicate::truthy_path(path))
    }

    /// `eq $key "literal"` (either operand order) where `$key` is a
    /// destructured range key: the predicate selects exactly the member
    /// with that key.
    fn range_key_equals_predicate(
        &self,
        left: &TemplateExpr,
        right: &TemplateExpr,
        negated: bool,
    ) -> Option<Predicate> {
        let (key_expr, literal) = match (literal_string(left), literal_string(right)) {
            (None, Some(literal)) => (left, literal),
            (Some(literal), None) => (right, literal),
            _ => return None,
        };
        let TemplateExpr::Variable(name) = key_expr.deparen() else {
            return None;
        };
        let binding = self
            .template_bindings
            .get(name)
            .or_else(|| self.template_bindings.get(name.trim_start_matches('$')))?;
        let AbstractValue::RangeKey(path) = binding else {
            return None;
        };
        let predicate = Predicate::from(Guard::RangeKeyEquals {
            path: path.clone(),
            key: literal.to_string(),
        });
        Some(if negated {
            predicate.negated()
        } else {
            predicate
        })
    }

    fn range_key_prefix_predicate(&self, args: &[TemplateExpr]) -> Option<Predicate> {
        let [prefix, key] = args else {
            return None;
        };
        let prefix = literal_string(prefix)?;
        let TemplateExpr::Variable(name) = key.deparen() else {
            return None;
        };
        let binding = self
            .template_bindings
            .get(name)
            .or_else(|| self.template_bindings.get(name.trim_start_matches('$')))?;
        let AbstractValue::RangeKey(path) = binding else {
            return None;
        };
        Some(Predicate::from(Guard::RangeKeyPrefix {
            path: path.clone(),
            prefix: prefix.to_string(),
        }))
    }

    fn positive_len_predicate(&self, function: &str, args: &[TemplateExpr]) -> Option<Predicate> {
        let [left, right] = args else {
            return None;
        };
        let (subject, bound) = match (function, left.deparen(), right.deparen()) {
            ("gt", subject, TemplateExpr::Literal(Literal::Int(bound)))
            | ("lt", TemplateExpr::Literal(Literal::Int(bound)), subject) => (subject, *bound),
            // The inclusive forms normalize to the strict bound below them.
            ("ge", subject, TemplateExpr::Literal(Literal::Int(bound)))
            | ("le", TemplateExpr::Literal(Literal::Int(bound)), subject) => {
                (subject, bound.checked_sub(1)?)
            }
            _ => return None,
        };
        if bound == 0
            && let TemplateExpr::Call {
                function,
                args: len_args,
            } = subject
            && function == "len"
            && let [len_subject] = len_args.as_slice()
        {
            return self.single_truthy_predicate(len_subject);
        }
        // `gt (keys X | len) N` is an exact member-count bound: `keys`
        // aborts rendering on non-maps, so the body runs exactly for
        // mappings with more than N members (external-secrets'
        // `gt (keys . | len) 1` securityContext gate).
        if bound >= 0
            && let Some(map_expr) = keys_len_subject(subject)
            && let Some(path) = self.single_resolved_values_path_expr(map_expr)
        {
            return Some(Predicate::from(Guard::MinMembers {
                path,
                bound: bound.checked_add(1)?,
            }));
        }
        None
    }

    fn default_truthy_predicate(&self, args: &[TemplateExpr]) -> Option<Predicate> {
        let [fallback, primary] = args else {
            return None;
        };
        Some(predicate_any(vec![
            self.exact_truthy_predicate(primary)?,
            self.exact_truthy_predicate(fallback)?,
        ]))
    }

    fn default_pipeline_truthy_predicate(&self, stages: &[TemplateExpr]) -> Option<Predicate> {
        let [primary, stage] = stages else {
            return None;
        };
        let TemplateExpr::Call { function, args } = stage.deparen() else {
            return None;
        };
        let [fallback] = args.as_slice() else {
            return None;
        };
        if function != "default" {
            return None;
        }
        Some(predicate_any(vec![
            self.exact_truthy_predicate(primary)?,
            self.exact_truthy_predicate(fallback)?,
        ]))
    }

    fn exact_truthy_predicate(&self, expr: &TemplateExpr) -> Option<Predicate> {
        self.condition_lowering_is_faithful(expr)
            .then(|| self.condition_predicate_expr(expr))
    }

    /// An ordered map merge unions its operands' keys, so the RESULT is
    /// nonempty exactly when some operand is. A definitely-empty literal
    /// destination (`mergeOverwrite (dict) a b`) contributes no keys and
    /// drops out; every remaining operand must decode exactly or the whole
    /// condition abstains.
    fn merge_truthy_predicate(&self, args: &[TemplateExpr]) -> Option<Predicate> {
        if args.len() < 2 {
            return None;
        }
        let mut arms = Vec::new();
        for arg in args {
            if let TemplateExpr::Call { function, args } = arg.deparen()
                && function == "dict"
                && args.is_empty()
            {
                continue;
            }
            arms.push(self.exact_truthy_predicate(arg)?);
        }
        (!arms.is_empty()).then(|| predicate_any(arms))
    }

    /// `coalesce` returns its first non-empty argument, so the RESULT is
    /// truthy exactly when some argument is truthy: the disjunction is the
    /// precise condition, unlike the generic all-paths-truthy fallback.
    fn coalesce_truthy_predicate(&self, args: &[TemplateExpr]) -> Option<Predicate> {
        let mut arms = Vec::new();
        for arg in args {
            arms.push(self.truthy_predicate(arg)?);
        }
        if arms.len() == 1 {
            return arms.pop();
        }
        (!arms.is_empty()).then_some(Predicate::Or(arms))
    }

    /// `Files.Get (printf "files/profile-%s.yaml" X)` truthiness decodes
    /// to a FINITE predicate: the chart ships a fixed file set, so the
    /// read is non-empty exactly when X names one of the matching files'
    /// captured segments. With several candidate paths for X (a
    /// `coalesce`), the union over paths is wider than the render-time
    /// pick, which rows tolerate; its negation only holds when NO
    /// candidate carries a valid name — states where rendering fails for
    /// every pick — so fail-branch negation stays sound.
    fn files_get_printf_predicate(&self, args: &[TemplateExpr]) -> Option<Predicate> {
        let [arg] = args else {
            return None;
        };
        let TemplateExpr::Call {
            function,
            args: printf_args,
        } = arg.deparen()
        else {
            return None;
        };
        let [format, subject] = printf_args.as_slice() else {
            return None;
        };
        if function != "printf" {
            return None;
        }
        let TemplateExpr::Literal(Literal::String(format) | Literal::RawString(format)) =
            format.deparen()
        else {
            return None;
        };
        let (prefix, suffix) = single_string_verb_split(format)?;
        let subject_paths = self.paths_for_expr(subject);
        if subject_paths.is_empty() {
            return None;
        }
        let names: Vec<String> = self
            .fragment_context
            .analysis_db
            .file_source_paths()
            .into_iter()
            .filter_map(|path| {
                path.strip_prefix(prefix)
                    .and_then(|rest| rest.strip_suffix(suffix))
                    .filter(|middle| !middle.is_empty())
                    .map(str::to_string)
            })
            .collect();
        if names.is_empty() {
            return None;
        }
        let mut arms = Vec::new();
        for path in &subject_paths {
            for name in &names {
                arms.push(Predicate::from(Guard::Eq {
                    path: path.clone(),
                    value: GuardValue::string(name),
                }));
            }
        }
        if arms.len() == 1 {
            return arms.pop();
        }
        Some(Predicate::Or(arms))
    }

    fn and_predicate(&self, args: &[TemplateExpr]) -> Option<Predicate> {
        let mut predicates = args
            .iter()
            .filter_map(|arg| self.condition_predicate(arg))
            .collect::<Vec<_>>();
        if predicates.is_empty() {
            return None;
        }
        // Statically true conjuncts (`and $shouldContinue …` where the
        // local's reduction is `True`) carry nothing: dropping them keeps
        // the remaining conjunct in its exact single-predicate shape.
        predicates.retain(|predicate| !matches!(predicate, Predicate::True));
        Some(Predicate::all(predicates))
    }

    fn not_predicate(&self, args: &[TemplateExpr]) -> Option<Predicate> {
        let [arg] = args else {
            return None;
        };

        match arg.deparen() {
            TemplateExpr::Call { function, args } if function == "empty" => self
                .empty_predicate(args)
                .map(|predicate| predicate.negated()),
            TemplateExpr::Call { function, args } if function == "or" => {
                // De Morgan over EXACT per-disjunct decodes: when every
                // disjunct lowers faithfully, each negates precisely and
                // the conjunction stays flat for guard extraction —
                // cilium's `not (or (eq … "Cluster") (eq … "Local"))`
                // traffic-policy gate needs the equality enum, not the
                // truthiness weakening the fallback lowers to. A truthy
                // stand-in for an undecodable disjunct must never be
                // negated, hence the faithfulness gate.
                if args
                    .iter()
                    .all(|arg| self.condition_lowering_is_faithful(arg))
                    && let Some(negated) = args
                        .iter()
                        .map(|arg| {
                            self.condition_predicate(arg)
                                .map(|predicate| predicate.negated())
                        })
                        .collect::<Option<Vec<_>>>()
                {
                    return Some(Predicate::all(negated));
                }
                self.negated_or_predicate(args)
            }
            TemplateExpr::Call { function, args } if function == "eq" => {
                self.value_comparison_predicate(args, true)
            }
            TemplateExpr::Call { function, args } if function == "ne" => {
                self.value_comparison_predicate(args, false)
            }
            // `not (typeIs …)` negates the TYPE TEST; degrading it to a
            // negated truthiness would conflate "not this type" with
            // "falsy".
            TemplateExpr::Call { function, args }
                if function == "typeIs" || function == "kindIs" =>
            {
                self.type_is_predicate(args).map(|p| p.negated())
            }
            TemplateExpr::Call { function, args } if function == "hasKey" => {
                self.has_key_predicate(args).map(|p| p.negated())
            }
            TemplateExpr::Call { function, args }
                if function == "regexMatch" || function == "mustRegexMatch" =>
            {
                self.regex_match_predicate(args).map(|p| p.negated())
            }
            TemplateExpr::Call { function, args } if function == "has" => self
                .helper_literal_membership_predicate(args)
                .map(|predicate| predicate.negated())
                .or_else(|| {
                    self.single_truthy_predicate(arg)
                        .map(|predicate| predicate.negated())
                }),
            // The piped membership spelling negates the same equality
            // disjunction as the call form; the general fallback below
            // would degrade it to a negated truthiness, which fires on
            // FALSY subjects that are perfectly valid members' complements
            // (cilium's kvstoreMode must-be-internal-or-external check).
            TemplateExpr::Pipeline(stages)
                if self.pipeline_membership_predicate(stages).is_some() =>
            {
                self.pipeline_membership_predicate(stages)
                    .map(|predicate| predicate.negated())
            }
            TemplateExpr::Call { function, args } if function == "and" => {
                self.and_predicate(args).map(|p| p.negated())
            }
            // `not (toString X)` / `not (X | toString)` negates the
            // RENDERING test; the raw-truthiness fallback below would fire
            // on raw false, which stringifies truthy. An undecodable
            // stringification abstains for the same reason.
            TemplateExpr::Call { function, args } if function == "toString" && args.len() == 1 => {
                self.tostring_truthy_predicate(args.first()?)
                    .map(|predicate| predicate.negated())
            }
            TemplateExpr::Pipeline(stages)
                if matches!(
                    stages.last().map(TemplateExpr::deparen),
                    Some(TemplateExpr::Call { function, args })
                        if function == "toString" && args.is_empty()
                ) =>
            {
                self.tostring_pipeline_truthy_predicate(stages)
                    .map(|predicate| predicate.negated())
            }
            // A local's negation lowers through its stored truthy
            // reduction — the same trust the positive Variable lowering
            // extends (`not $stateful` selecting airflow's Deployment
            // arm). Only approximation-free reductions qualify: negating
            // an approximate marker would fire in states the marker never
            // described. The path fallback below would mint a truthy
            // stand-in over the flowing paths, which negation must not do.
            TemplateExpr::Variable(name)
                if self
                    .variable_truthy_reduction(name)
                    .is_some_and(|reduction| !reduction.contains_approximation()) =>
            {
                self.variable_truthy_reduction(name).map(Predicate::negated)
            }
            _ => {
                if let Some(predicate) = self.root_field_truthy_predicate(arg) {
                    return Some(predicate.negated());
                }
                let paths = self.paths_for_expr(arg);
                if paths.len() == 1 {
                    return paths
                        .into_iter()
                        .next()
                        .map(|path| Predicate::truthy_path(path).negated());
                }
                // A grouped selector chain reads the receiver AND the leaf
                // (`($config.http).tls.enabled` yields `…http` beside
                // `…http.tls.enabled`). On an ancestor CHAIN the leaf's
                // truthiness is the exact conjunction — a truthy leaf makes
                // every ancestor a nonempty container — so the negation is
                // the leaf's falsiness. Unrelated path sets still abstain.
                if let Some(leaf) = ancestor_chain_leaf(&paths) {
                    return Some(Predicate::truthy_path(leaf).negated());
                }
                None
            }
        }
    }

    fn variable_truthy_reduction(&self, name: &str) -> Option<&Predicate> {
        self.template_truthy_reductions.get(name).or_else(|| {
            self.template_truthy_reductions
                .get(name.trim_start_matches('$'))
        })
    }

    fn negated_or_predicate(&self, args: &[TemplateExpr]) -> Option<Predicate> {
        let predicates = args
            .iter()
            .map(|arg| {
                self.single_truthy_predicate(arg)
                    .map(|predicate| predicate.negated())
            })
            .collect::<Option<Vec<_>>>()?;
        (!predicates.is_empty()).then(|| Predicate::all(predicates))
    }

    fn empty_predicate(&self, args: &[TemplateExpr]) -> Option<Predicate> {
        let [arg] = args else {
            return None;
        };
        self.single_truthy_predicate(arg)
            .map(|predicate| predicate.negated())
    }

    fn has_key_predicate(&self, args: &[TemplateExpr]) -> Option<Predicate> {
        let [map, key] = args else {
            return None;
        };
        // A literal key, or a variable statically bound to one string (an
        // unrolled traversal's `$elem`).
        let key = match key.deparen() {
            TemplateExpr::Literal(Literal::String(key) | Literal::RawString(key)) => key.clone(),
            key => self.constant_scalar(key)?,
        };
        self.with_body_fragment_value_expr(map)
            .and_then(|value| value_has_key(&value, &key))
    }

    /// `regexMatch pattern subject` over a literal pattern and one
    /// values-backed subject is a pattern test on the path. `regexMatch`
    /// type-asserts a string subject, so the guard holding also implies
    /// string-ness; its NEGATION stays a raw predicate for fail lowering.
    fn regex_match_predicate(&self, args: &[TemplateExpr]) -> Option<Predicate> {
        let [pattern, subject] = args else {
            return None;
        };
        let pattern = literal_string(pattern)?;
        if let Some(predicate) = self.type_descriptor_regex_predicate(pattern, subject) {
            return Some(predicate);
        }
        let path = match self.with_body_fragment_value_expr(subject)? {
            AbstractValue::ValuesPath(path) if !path.is_empty() => path,
            // The subject is a destructured range KEY: the pattern applies
            // per key of the ranged collection (traefik's uppercase
            // `ingressRoute` gate).
            AbstractValue::RangeKey(collection) if !collection.is_empty() => {
                return Some(Predicate::from(Guard::RangeKeyMatches {
                    path: collection,
                    pattern: pattern.to_string(),
                }));
            }
            _ => return None,
        };
        // A subject that reached this consumer through `tpl` carries its
        // rendered OUTPUT here, not the raw program: the pattern then
        // constrains the render, and a raw value carrying a template action
        // is admitted (redis-ha `masterGroupName: "{{ .Release.Name }}"`).
        // The string contract from `tpl`'s input assertion still stands.
        let templated = self.subject_is_derived_text(subject, &path);
        Some(Predicate::from(Guard::MatchesPattern {
            path,
            pattern: pattern.to_string(),
            templated,
        }))
    }

    /// `hasPrefix`/`hasSuffix` over a literal affix and a values-path
    /// subject is an anchored literal pattern test on the value's rendered
    /// text (datadog's `hasPrefix "unix:" .` OTLP endpoint terminal, where
    /// the dot is the caller's bound endpoint scalar).
    fn string_affix_predicate(&self, args: &[TemplateExpr], suffix: bool) -> Option<Predicate> {
        let [affix, subject] = args else {
            return None;
        };
        let affix = literal_string(affix)?;
        let path = match self.with_body_fragment_value_expr(subject)? {
            AbstractValue::ValuesPath(path) if !path.is_empty() => path,
            _ => return None,
        };
        let templated = self.subject_is_derived_text(subject, &path);
        let pattern = if suffix {
            format!("{}$", escape_regex_literal(affix))
        } else {
            format!("^{}", escape_regex_literal(affix))
        };
        Some(Predicate::from(Guard::MatchesPattern {
            path,
            pattern,
            templated,
        }))
    }

    fn contains_predicate(&self, args: &[TemplateExpr]) -> Option<Predicate> {
        let [needle, subject] = args else {
            return None;
        };
        let needle = literal_string(needle)?;
        let path = match self.with_body_fragment_value_expr(subject)? {
            AbstractValue::ValuesPath(path) if !path.is_empty() => path,
            _ => return None,
        };
        Some(Predicate::from(Guard::MatchesPattern {
            path,
            pattern: escape_regex_literal(needle),
            templated: false,
        }))
    }

    /// Whether the subject expression's resolved `path` reached this site
    /// through a derived-text transform (`tpl`, a stringification) recorded
    /// on a bound local's output metadata.
    fn subject_is_derived_text(&self, subject: &TemplateExpr, path: &str) -> bool {
        let TemplateExpr::Variable(name) = subject.deparen() else {
            return false;
        };
        let name = name.trim_start_matches('$');
        self.template_output_meta
            .get(name)
            .and_then(|by_path| by_path.get(path))
            .is_some_and(|meta| meta.derived_text || meta.shape_erased)
    }

    /// The single string a statically known scalar expression denotes:
    /// folded literal members, unrolled iteration bindings, and constant
    /// `len`/`add1` results. Values-backed reads never qualify.
    fn constant_scalar(&self, expr: &TemplateExpr) -> Option<String> {
        let value = eval_expr(expr, &self.expression_eval_env()).value?;
        let AbstractValue::StringSet(strings) = value else {
            return None;
        };
        let mut strings = strings.iter();
        match (strings.next(), strings.next()) {
            (Some(text), None) => Some(text.clone()),
            _ => None,
        }
    }

    fn or_predicate(&self, args: &[TemplateExpr]) -> Option<Predicate> {
        let mut truthy_paths = BTreeSet::new();
        let mut alternatives = Vec::new();
        for arg in args {
            let paths = self.paths_for_expr(arg);
            if !paths.is_empty() && !matches!(arg.deparen(), TemplateExpr::Call { .. }) {
                // An exactly decodable pipeline disjunct (`… | toString`)
                // must not collapse to raw truthiness: the RENDERING's
                // truthiness differs from the value's (cilium's
                // removed-option guards abort on a truthy "false").
                if matches!(arg.deparen(), TemplateExpr::Pipeline(_))
                    && let Some(exact) = self.condition_predicate(arg)
                {
                    alternatives.push(exact);
                    continue;
                }
                truthy_paths.extend(paths);
                continue;
            }
            alternatives.push(self.condition_predicate(arg)?);
        }
        if !truthy_paths.is_empty() {
            let predicate = Predicate::Or(
                truthy_paths
                    .into_iter()
                    .map(Predicate::truthy_path)
                    .collect(),
            );
            alternatives.push(predicate);
        }
        (!alternatives.is_empty()).then_some(Predicate::Or(alternatives))
    }

    fn type_is_predicate(&self, args: &[TemplateExpr]) -> Option<Predicate> {
        let TemplateExpr::Literal(Literal::String(type_name) | Literal::RawString(type_name)) =
            args.first()?.deparen()
        else {
            return None;
        };
        let schema_type = type_is_schema_type(args.first());
        if type_name != "invalid" && schema_type.is_none() {
            return None;
        }
        let predicates = args
            .iter()
            .skip(1)
            .flat_map(|arg| self.paths_for_expr(arg))
            .map(|path| match &schema_type {
                Some(schema_type) => Predicate::from(Guard::TypeIs {
                    path,
                    schema_type: schema_type.clone(),
                }),
                None => invalid_kind_predicate(path),
            })
            .collect::<Vec<_>>();
        (!predicates.is_empty()).then(|| Predicate::all(predicates))
    }

    /// `eq (include "mode" .) "literal"`: when the called helper is a pure
    /// LITERAL DISPATCH invoked with a root-carrying context, the
    /// comparison selects exactly the arms returning that literal — the
    /// predicate is the any-of of their branch conditions, each conjoined
    /// with the negations of the arms before them (the chain is ordered
    /// and exclusive). Every arm header must decode faithfully, or the
    /// comparison abstains: a degraded arm would make those negations
    /// select states the helper never maps to the literal.
    fn helper_literal_dispatch_predicate(
        &self,
        left: &TemplateExpr,
        right: &TemplateExpr,
        negated: bool,
    ) -> Option<Predicate> {
        let (name, target) = match (helper_root_call(left), helper_root_call(right)) {
            (Some(name), None) => (name, literal_string(right)?),
            (None, Some(name)) => (name, literal_string(left)?),
            _ => return None,
        };
        // The dispatch helper reads `.Values.*` absolutely, so its
        // conditions keep their meaning only under a root dot.
        if !self
            .current_dot_binding
            .as_ref()
            .is_none_or(|dot| matches!(dot, AbstractValue::RootContext))
        {
            return None;
        }
        if HELPER_DISPATCH_DEPTH.with(std::cell::Cell::get) >= MAX_HELPER_DISPATCH_DEPTH {
            return None;
        }
        let arms = crate::helper_literal_dispatch::helper_literal_dispatch(
            self.fragment_context.analysis_db,
            name,
        )?;
        HELPER_DISPATCH_DEPTH.with(|depth| depth.set(depth.get() + 1));
        let predicate = self.literal_dispatch_arms_predicate(&arms, &|arm| arm.literal == target);
        HELPER_DISPATCH_DEPTH.with(|depth| depth.set(depth.get() - 1));
        let predicate = predicate?;
        Some(if negated {
            predicate.negated()
        } else {
            predicate
        })
    }

    /// A bare `include "name" .` used AS a condition is truthy exactly when
    /// the called helper emits non-empty text. For a pure literal dispatch
    /// under a root context, the truthy states are the arms with non-empty
    /// output, each conjoined with its prior arms' negations (redis'
    /// `if (include "redis.createConfigmap" .)` document gate reduces to
    /// `empty .Values.existingConfigmap`). An arm whose trimmed literal is
    /// empty but which still collected whitespace abstains: its render
    /// truthiness would depend on the chain's trim markers.
    fn include_truthy_predicate(&self, expr: &TemplateExpr) -> Option<Predicate> {
        let name = helper_root_call(expr)?;
        if !self
            .current_dot_binding
            .as_ref()
            .is_none_or(|dot| matches!(dot, AbstractValue::RootContext))
        {
            return None;
        }
        if HELPER_DISPATCH_DEPTH.with(std::cell::Cell::get) >= MAX_HELPER_DISPATCH_DEPTH {
            return None;
        }
        let arms = crate::helper_literal_dispatch::helper_literal_dispatch(
            self.fragment_context.analysis_db,
            name,
        )?;
        if arms
            .iter()
            .any(|arm| arm.literal.is_empty() && !arm.raw_empty)
        {
            return None;
        }
        HELPER_DISPATCH_DEPTH.with(|depth| depth.set(depth.get() + 1));
        let predicate = self.literal_dispatch_arms_predicate(&arms, &|arm| !arm.literal.is_empty());
        HELPER_DISPATCH_DEPTH.with(|depth| depth.set(depth.get() - 1));
        predicate
    }

    /// The piped membership spelling `list L1 L2 … | has X`: the pipeline
    /// passes the literal list as `has`'s LAST argument, so it decodes to
    /// the same equality disjunction as the call form (cilium's
    /// netkit-datapath tproxy exclusion tests membership positively).
    fn pipeline_membership_predicate(&self, stages: &[TemplateExpr]) -> Option<Predicate> {
        let [haystack, has] = stages else {
            return None;
        };
        let TemplateExpr::Call { function, args } = has.deparen() else {
            return None;
        };
        if function != "has" || args.len() != 1 {
            return None;
        }
        let [needle] = args.as_slice() else {
            return None;
        };
        self.helper_literal_membership_predicate(&[needle.clone(), haystack.clone()])
    }

    #[expect(
        clippy::too_many_lines,
        reason = "keeping this semantic operation together makes its state transitions easier to audit"
    )]
    fn helper_literal_membership_predicate(&self, args: &[TemplateExpr]) -> Option<Predicate> {
        let [needle, haystack] = args else {
            return None;
        };
        // `has X (list L1 L2 …)` over a direct selector with typed scalar
        // literals is EXACTLY "X equals one of the literals" (Sprig `has`
        // is deep equality per item). Typed targets keep non-string
        // literals precise: airflow probes explicit Boolean flags with
        // `has .Values.…enabled (list true false)`.
        if let TemplateExpr::Call {
            function,
            args: list_args,
        } = haystack.deparen()
            && matches!(function.as_str(), "list" | "tuple")
            && !list_args.is_empty()
            && matches!(
                needle.deparen(),
                TemplateExpr::Field(_) | TemplateExpr::Selector { .. } | TemplateExpr::Variable(_)
            )
            && let Some(values) = list_args
                .iter()
                .map(literal_guard_value)
                .collect::<Option<Vec<_>>>()
        {
            let mut paths = self.paths_for_expr(needle).into_iter();
            let path = paths.next()?;
            if paths.next().is_some() {
                return None;
            }
            return Some(predicate_any(
                values
                    .into_iter()
                    .map(|value| {
                        Predicate::from(Guard::Eq {
                            path: path.clone(),
                            value,
                        })
                    })
                    .collect(),
            ));
        }
        // The dual direction: a literal needle probed against a VALUES
        // list (`has "cookie-secret" .Values.config.requiredSecretKeys`).
        // Sprig `has` returns false on a nil haystack and aborts on
        // non-lists, so the guard holds exactly for arrays carrying the
        // literal (oauth2-proxy's requiredSecretKeys gates).
        if matches!(
            haystack.deparen(),
            TemplateExpr::Field(_) | TemplateExpr::Selector { .. }
        ) && let Some(value) = literal_guard_value(needle)
        {
            let mut paths = self.paths_for_expr(haystack).into_iter();
            let path = paths.next()?;
            if paths.next().is_some() {
                return None;
            }
            return Some(Predicate::from(Guard::ContainsEquals { path, value }));
        }
        let targets: Vec<String> = match haystack.deparen() {
            TemplateExpr::Call { function, args } if function == "list" && !args.is_empty() => args
                .iter()
                .map(literal_membership_string)
                .collect::<Option<Vec<_>>>()?,
            TemplateExpr::Variable(name) => {
                let AbstractValue::List(items) = self
                    .template_bindings
                    .get(name)
                    .or_else(|| self.template_bindings.get(name.trim_start_matches('$')))?
                else {
                    return None;
                };
                let mut targets = Vec::new();
                for item in items {
                    let strings = item.strings();
                    if strings.is_empty() {
                        return None;
                    }
                    targets.extend(strings);
                }
                targets
            }
            _ => return None,
        };
        if targets.is_empty() {
            return Some(Predicate::False);
        }

        if let TemplateExpr::Call { function, args } = needle.deparen()
            && function == "quote"
            && let [subject] = args.as_slice()
            && targets
                .iter()
                .all(|target| target.is_empty() || target == "\"\"")
            && targets.iter().any(|target| target == "\"\"")
        {
            let mut paths = self.paths_for_expr(subject).into_iter();
            let path = paths.next()?;
            if paths.next().is_some() {
                return None;
            }
            return Some(Predicate::Or(vec![
                Predicate::from(Guard::Absent { path: path.clone() }),
                Predicate::from(Guard::Eq {
                    path: path.clone(),
                    value: GuardValue::Null,
                }),
                Predicate::from(Guard::Eq {
                    path,
                    value: GuardValue::string(""),
                }),
            ]));
        }

        if helper_root_call(needle).is_none() {
            if !matches!(
                needle.deparen(),
                TemplateExpr::Field(_) | TemplateExpr::Selector { .. } | TemplateExpr::Variable(_)
            ) {
                return None;
            }
            let mut paths = self.paths_for_expr(needle).into_iter();
            let path = paths.next()?;
            if paths.next().is_some() {
                return None;
            }
            let predicates = targets
                .into_iter()
                .map(|target| {
                    Predicate::from(Guard::Eq {
                        path: path.clone(),
                        value: GuardValue::string(target),
                    })
                })
                .collect();
            return Some(predicate_any(predicates));
        }

        let name = helper_root_call(needle)?;
        if !self
            .current_dot_binding
            .as_ref()
            .is_none_or(|dot| matches!(dot, AbstractValue::RootContext))
            || HELPER_DISPATCH_DEPTH.with(std::cell::Cell::get) >= MAX_HELPER_DISPATCH_DEPTH
        {
            return None;
        }
        let arms = crate::helper_literal_dispatch::helper_literal_dispatch(
            self.fragment_context.analysis_db,
            name,
        )?;
        HELPER_DISPATCH_DEPTH.with(|depth| depth.set(depth.get() + 1));
        let predicates = targets
            .into_iter()
            .map(|target| self.literal_dispatch_arms_predicate(&arms, &|arm| arm.literal == target))
            .collect::<Option<Vec<_>>>();
        HELPER_DISPATCH_DEPTH.with(|depth| depth.set(depth.get() - 1));
        let mut predicates = predicates?;
        predicates.retain(|predicate| !matches!(predicate, Predicate::False));
        match predicates.as_slice() {
            [] => Some(Predicate::False),
            [predicate] => Some(predicate.clone()),
            _ => Some(Predicate::Or(predicates)),
        }
    }

    fn literal_dispatch_arms_predicate(
        &self,
        arms: &[crate::helper_literal_dispatch::LiteralDispatchArm],
        select: &dyn Fn(&crate::helper_literal_dispatch::LiteralDispatchArm) -> bool,
    ) -> Option<Predicate> {
        let mut prior: Vec<Predicate> = Vec::new();
        let mut matching: Vec<Predicate> = Vec::new();
        for arm in arms {
            match &arm.header {
                Some(header) => {
                    if !self.condition_lowering_is_faithful(header.expr()) {
                        return None;
                    }
                    let condition = self.condition_predicate_expr(header.expr());
                    if select(arm) {
                        let mut conjuncts: Vec<Predicate> =
                            prior.iter().map(Predicate::negated).collect();
                        conjuncts.push(condition.clone());
                        matching.push(Predicate::all(conjuncts));
                    }
                    prior.push(condition);
                }
                None => {
                    if select(arm) {
                        matching.push(Predicate::all(
                            prior.iter().map(Predicate::negated).collect(),
                        ));
                    }
                }
            }
        }
        Some(match matching.len() {
            // No arm is selected: the dispatch is total, so the condition
            // can never hold.
            0 => Predicate::False,
            1 => matching.remove(0),
            _ => Predicate::Or(matching),
        })
    }

    fn truthy_predicate(&self, expr: &TemplateExpr) -> Option<Predicate> {
        if let TemplateExpr::Literal(literal) = expr.deparen() {
            return Some(bool_predicate(literal_is_truthy(literal)));
        }
        if let Some(predicate) = self.root_field_truthy_predicate(expr) {
            return Some(predicate);
        }
        if let TemplateExpr::Variable(name) = expr.deparen()
            && let Some(predicate) = self.template_truthy_reductions.get(name).or_else(|| {
                self.template_truthy_reductions
                    .get(name.trim_start_matches('$'))
            })
        {
            return Some(predicate.clone());
        }
        if let TemplateExpr::Variable(name) = expr.deparen()
            && let Some(predicate) = self.get_binding_truthy_predicate(name)
        {
            return Some(predicate);
        }
        // A local holding an ordered merge is nonempty exactly when SOME
        // layer is (KPS's `if $additionalAnnotations` over a fresh-dict
        // `mergeOverwrite`): the all-paths conjunction below would demand
        // every layer at once. Undecodable layers abstain to the
        // approximate lane instead of riding that wrong conjunction.
        // Selectors project the same layered form member-wise (airflow's
        // candidate helper tests `.securityContexts.pod` on a merged
        // workers context), so the lane keys on the VALUE, not the
        // expression spelling.
        if let TemplateExpr::Variable(_) = expr.deparen()
            && let Some(AbstractValue::MergedLayers(layers)) =
                eval_expr(expr, &self.expression_eval_env()).value
        {
            return merged_layers_truthy_predicate(&layers);
        }
        // Selectors project the same layered form member-wise (airflow's
        // candidate helper tests `.securityContexts.pod` on a merged
        // workers context). Unlike the local-variable lane, an undecodable
        // layer set FALLS THROUGH to the generic all-paths conjunction:
        // ranged captures concretize member wildcards there, and dropping
        // the predicate entirely would silence their existential arms
        // (airflow's per-set labels under the merged worker context).
        if matches!(
            expr.deparen(),
            TemplateExpr::Field(_) | TemplateExpr::Selector { .. }
        ) && let Some(AbstractValue::MergedLayers(layers)) =
            eval_expr(expr, &self.expression_eval_env()).value
            && let Some(predicate) = merged_layers_truthy_predicate(&layers)
        {
            return Some(predicate);
        }
        // A first-truthy selection chain is truthy exactly when SOME
        // candidate is (`default` returns its fallback verbatim, so a
        // falsy chain means every candidate was falsy): the all-paths
        // conjunction below would demand every candidate at once, and a
        // fail capture inheriting that conjunct could never co-hold with
        // the chain's own `¬truthy` selection conjuncts (the kyverno
        // `imagePullSecrets | default global` helper dot).
        if matches!(
            expr.deparen(),
            TemplateExpr::Variable(_) | TemplateExpr::Field(_) | TemplateExpr::Selector { .. }
        ) && let Some(AbstractValue::FirstTruthy(candidates)) =
            eval_expr(expr, &self.expression_eval_env()).value
            && let Some(predicate) = first_truthy_truthy_predicate(&candidates)
        {
            return Some(predicate);
        }
        let paths = self.paths_for_expr(expr);
        if paths.is_empty() {
            return None;
        }
        Some(Predicate::all(
            paths.into_iter().map(Predicate::truthy_path).collect(),
        ))
    }

    fn root_field_truthy_predicate(&self, expr: &TemplateExpr) -> Option<Predicate> {
        let explicit_root = matches!(self.current_dot_binding, Some(AbstractValue::RootContext));
        if !self
            .current_dot_binding
            .as_ref()
            .is_none_or(|dot| matches!(dot, AbstractValue::RootContext))
        {
            return None;
        }
        let field = match expr.deparen() {
            TemplateExpr::Field(path) => path.as_slice(),
            TemplateExpr::Selector { operand, path } if matches!(operand.as_ref(), TemplateExpr::Variable(variable) if variable.is_empty()) => {
                path.as_slice()
            }
            _ => return None,
        };
        let [field] = field else {
            return None;
        };
        if let Some(predicate) = self.root_truthy_predicates.get(field) {
            return Some(predicate.clone());
        }
        if self.root_bindings.contains_key(field)
            || matches!(
                field.as_str(),
                "Capabilities"
                    | "Chart"
                    | "Files"
                    | "Release"
                    | "Subcharts"
                    | "Template"
                    | "Values"
            )
        {
            return None;
        }

        // Helm's explicit root context has a fixed set of built-in fields. A
        // custom field is absent until a tracked `set` mutation creates it.
        // An unresolved dot is not proof of root identity and must abstain.
        explicit_root.then_some(Predicate::False)
    }

    fn root_field_dispatch_predicate(
        &self,
        left: &TemplateExpr,
        right: &TemplateExpr,
        negated: bool,
    ) -> Option<Predicate> {
        let (field, value) = match (self.root_dispatch_field(left), guard_value_literal(right)) {
            (Some(field), Some(value)) => (field, value),
            _ => match (self.root_dispatch_field(right), guard_value_literal(left)) {
                (Some(field), Some(value)) => (field, value),
                _ => return None,
            },
        };
        let dispatch = self.root_value_dispatches.get(field)?;
        let selected = predicate_any(
            dispatch
                .arms
                .iter()
                .filter(|(_, literal)| *literal == value)
                .map(|(condition, _)| condition.clone())
                .collect(),
        );
        Some(if negated {
            selected.negated()
        } else {
            selected
        })
    }

    /// A single-segment root-context field (`.mode`) under a root (or
    /// unresolved) dot that carries a joined value dispatch.
    fn root_dispatch_field<'expr>(&self, expr: &'expr TemplateExpr) -> Option<&'expr str> {
        if !self
            .current_dot_binding
            .as_ref()
            .is_none_or(|dot| matches!(dot, AbstractValue::RootContext))
        {
            return None;
        }
        let field = match expr.deparen() {
            TemplateExpr::Field(path) => path.as_slice(),
            TemplateExpr::Selector { operand, path } if matches!(operand.as_ref(), TemplateExpr::Variable(variable) if variable.is_empty()) => {
                path.as_slice()
            }
            _ => return None,
        };
        let [field] = field else {
            return None;
        };
        self.root_value_dispatches
            .contains_key(field)
            .then_some(field.as_str())
    }

    fn get_binding_truthy_predicate(&self, name: &str) -> Option<Predicate> {
        let binding = self.get_bindings.get(name.trim_start_matches('$'))?;
        let keys = self.range_domains.get(&binding.key_var)?;
        let predicates = keys
            .iter()
            .map(|key| {
                Predicate::truthy_path(helm_schema_core::append_value_path(&binding.base, key))
            })
            .collect::<Vec<_>>();
        match predicates.as_slice() {
            [] => None,
            [predicate] => Some(predicate.clone()),
            _ => Some(Predicate::Or(predicates)),
        }
    }

    /// Sound subsets of a comparison's NEGATION: the int-cast lanes
    /// region-flip exactly (¬(x > N) ⇔ x < N+1 over the coerced value,
    /// ¬(x == N) ⇔ x ≠ N, ¬(x ≠ N) ⇔ x == N); other comparison families
    /// abstain under negation.
    fn negated_comparison_sound_subset(&self, expr: &TemplateExpr) -> Vec<Guard> {
        let subset = self.int_cast_comparison_region_subset(expr, true);
        if !subset.is_empty() {
            return subset;
        }
        let TemplateExpr::Call { function, args } = expr.deparen() else {
            return Vec::new();
        };
        match function.as_str() {
            "eq" => self.int_cast_not_equal_subset(args),
            "ne" => self.int_cast_equality_region(args),
            _ => Vec::new(),
        }
    }

    /// Sound positive strengthenings of otherwise-undecodable comparison
    /// conditions, tried in order of exactness.
    fn comparison_sound_subset(&self, expr: &TemplateExpr) -> Vec<Guard> {
        let subset = self.semver_comparison_sound_subset(expr);
        if !subset.is_empty() {
            return subset;
        }
        let subset = self.int_cast_comparison_sound_subset(expr);
        if !subset.is_empty() {
            return subset;
        }
        let subset = self.len_comparison_sound_subset(expr);
        if !subset.is_empty() {
            return subset;
        }
        let subset = self.int_cast_inequality_sound_subset(expr);
        if !subset.is_empty() {
            return subset;
        }
        let subset = self.int_cast_equality_sound_subset(expr);
        if !subset.is_empty() {
            return subset;
        }
        let subset = self.include_dispatch_semver_sound_subset(expr);
        if !subset.is_empty() {
            return subset;
        }
        self.negated_membership_sound_subset(expr)
    }

    /// `eq (include "helper" .) "LIT"` over a pure literal dispatch whose
    /// non-else arms are `semverCompare "<C" (PATH | default
    /// .Capabilities.KubeVersion.Version)` upper bounds: selecting the
    /// ELSE arm's literal requires every bound to fail, and a PATH
    /// matching every flipped `>=C` constraint certainly fails them all —
    /// a sound subset usable in fail position (oauth2-proxy's
    /// `capabilities.ingress.apiVersion` gate on the legacy extraPaths
    /// abort). The capability-default lane stays out of the subset: with
    /// PATH unset the selection is cluster-dependent.
    fn include_dispatch_semver_sound_subset(&self, expr: &TemplateExpr) -> Vec<Guard> {
        let TemplateExpr::Call { function, args } = expr.deparen() else {
            return Vec::new();
        };
        if function != "eq" {
            return Vec::new();
        }
        let [left, right] = args.as_slice() else {
            return Vec::new();
        };
        let (name, target) = match (helper_root_call(left), helper_root_call(right)) {
            (Some(name), None) => (name, literal_string(right)),
            (None, Some(name)) => (name, literal_string(left)),
            _ => return Vec::new(),
        };
        let Some(target) = target else {
            return Vec::new();
        };
        if !self
            .current_dot_binding
            .as_ref()
            .is_none_or(|dot| matches!(dot, AbstractValue::RootContext))
        {
            return Vec::new();
        }
        if HELPER_DISPATCH_DEPTH.with(std::cell::Cell::get) >= MAX_HELPER_DISPATCH_DEPTH {
            return Vec::new();
        }
        let Some(arms) = crate::helper_literal_dispatch::helper_literal_dispatch(
            self.fragment_context.analysis_db,
            name,
        ) else {
            return Vec::new();
        };
        let Some((else_arm, bounded_arms)) = arms.split_last() else {
            return Vec::new();
        };
        if else_arm.header.is_some()
            || else_arm.literal != target
            || bounded_arms.iter().any(|arm| arm.literal == target)
        {
            return Vec::new();
        }
        let mut subject_path: Option<String> = None;
        let mut guards = Vec::new();
        for arm in bounded_arms {
            let Some(header) = &arm.header else {
                return Vec::new();
            };
            let TemplateExpr::Call { function, args } = header.expr().deparen() else {
                return Vec::new();
            };
            let [constraint, subject] = args.as_slice() else {
                return Vec::new();
            };
            if function != "semverCompare" {
                return Vec::new();
            }
            let TemplateExpr::Literal(Literal::String(constraint)) = constraint.deparen() else {
                return Vec::new();
            };
            // `<X-0` opts prereleases into Masterminds' matching; the
            // flipped subset pattern only ever matches RELEASE versions,
            // and a release ≥ X certainly fails `<X-0` too, so the
            // prerelease marker drops out of the flipped bound.
            let Some(flipped) = constraint
                .strip_prefix('<')
                .filter(|rest| !rest.starts_with('='))
                .map(|rest| format!(">={}", rest.strip_suffix("-0").unwrap_or(rest)))
            else {
                return Vec::new();
            };
            let Some(path) = self.single_resolved_values_path_expr(subject) else {
                return Vec::new();
            };
            if subject_path.get_or_insert_with(|| path.clone()) != &path {
                return Vec::new();
            }
            let Some(pattern) = helm_schema_ast::semver_constraint_match_pattern(&flipped) else {
                return Vec::new();
            };
            guards.push(Guard::MatchesPattern {
                path,
                pattern,
                templated: false,
            });
        }
        guards
    }

    /// `gt (len .Values.x) N` admits a bounded string strengthening: a
    /// string of more than N CHARACTERS has more than N bytes, so it always
    /// satisfies Go's byte-length comparison (cilium's 32-character
    /// `cluster.name` bound). Long collections also satisfy the guard but
    /// have no pattern encoding, so they stay outside the subset. The
    /// inclusive comparators normalize by shifting the bound (traefik's
    /// `ge (len .Values.hub.token) 65` license gates).
    fn len_comparison_sound_subset(&self, expr: &TemplateExpr) -> Vec<Guard> {
        let TemplateExpr::Call { function, args } = expr.deparen() else {
            return Vec::new();
        };
        let form = match (function.as_str(), args.as_slice()) {
            ("gt" | "ge", [left, right]) => match right.deparen() {
                TemplateExpr::Literal(Literal::Int(bound)) => {
                    Some((function, left.deparen(), *bound))
                }
                _ => None,
            },
            ("lt" | "le", [left, right]) => match left.deparen() {
                TemplateExpr::Literal(Literal::Int(bound)) => {
                    Some((function, right.deparen(), *bound))
                }
                _ => None,
            },
            _ => None,
        };
        let Some((function, len_expr, bound)) = form else {
            return Vec::new();
        };
        let bound = match function.as_str() {
            "gt" | "lt" => bound,
            // `ge (len x) N` ⇔ `gt (len x) (N-1)`; overflow abstains.
            _ => match bound.checked_sub(1) {
                Some(bound) => bound,
                None => return Vec::new(),
            },
        };
        let TemplateExpr::Call { function, args } = len_expr else {
            return Vec::new();
        };
        if function != "len" || args.len() != 1 {
            return Vec::new();
        }
        let (Some(path), Ok(bound)) = (
            args.first()
                .and_then(|arg| self.single_resolved_values_path_expr(arg)),
            usize::try_from(bound),
        ) else {
            return Vec::new();
        };
        vec![Guard::MatchesPattern {
            path,
            pattern: format!("^[\\s\\S]{{{},}}$", bound + 1),
            templated: false,
        }]
    }

    /// `ne (int x) L` admits a raw-integer strengthening: an integer input
    /// is its own coercion, so a raw JSON integer different from the
    /// literal always satisfies the comparison (cilium's 255-or-511
    /// `maxConnectedClusters` check). Strings and other kinds coerce and
    /// stay outside the subset. The cast may sit behind a bound local.
    fn int_cast_inequality_sound_subset(&self, expr: &TemplateExpr) -> Vec<Guard> {
        let TemplateExpr::Call { function, args } = expr.deparen() else {
            return Vec::new();
        };
        if function != "ne" {
            return Vec::new();
        }
        self.int_cast_not_equal_subset(args)
    }

    /// The "coerced value differs from N" claim shared by `ne (int X) N`
    /// and the negation of `eq (int X) N`: a raw JSON integer other than
    /// the literal certainly satisfies it.
    fn int_cast_not_equal_subset(&self, args: &[TemplateExpr]) -> Vec<Guard> {
        let [left, right] = args else {
            return Vec::new();
        };
        let (cast_expr, literal) = match (left.deparen(), right.deparen()) {
            (cast, TemplateExpr::Literal(Literal::Int(literal)))
            | (TemplateExpr::Literal(Literal::Int(literal)), cast) => (cast, *literal),
            _ => return Vec::new(),
        };
        let Some(source) = self.int_cast_operand(cast_expr) else {
            return Vec::new();
        };
        let mut guards = vec![
            Guard::TypeIs {
                path: source.path.clone(),
                schema_type: "integer".to_string(),
            },
            Guard::NotEq {
                path: source.path.clone(),
                value: helm_schema_core::GuardValue::Int(literal),
            },
        ];
        // A literal `default` substitutes for a raw 0 (numerically empty)
        // BEFORE the comparison: when the fallback equals the literal, a
        // raw 0 no longer satisfies `ne`, so exclude it from the claim.
        if literal != 0 && source.default_int == Some(literal) {
            guards.push(Guard::NotEq {
                path: source.path,
                value: helm_schema_core::GuardValue::Int(0),
            });
        }
        guards
    }

    /// `eq (int X) N` certainly holds for a RAW integer equal to N, so a
    /// fail arm keyed on the [`Guard::IntGt`]`{N-1}` ∧ [`Guard::IntLt`]
    /// `{N+1}` region pair keeps firing there (kyverno's `eq (int .) 0`
    /// replicas terminal through `{{ template … }}`). Coercible
    /// non-integers — booleans, fractional floats, parseable strings —
    /// also satisfy the equality; they stay a sound abstention.
    fn int_cast_equality_sound_subset(&self, expr: &TemplateExpr) -> Vec<Guard> {
        let TemplateExpr::Call { function, args } = expr.deparen() else {
            return Vec::new();
        };
        if function != "eq" {
            return Vec::new();
        }
        self.int_cast_equality_region(args)
    }

    fn int_cast_equality_region(&self, args: &[TemplateExpr]) -> Vec<Guard> {
        let [left, right] = args else {
            return Vec::new();
        };
        let (cast_expr, literal) = match (left.deparen(), right.deparen()) {
            (cast, TemplateExpr::Literal(Literal::Int(literal)))
            | (TemplateExpr::Literal(Literal::Int(literal)), cast) => (cast, *literal),
            _ => return Vec::new(),
        };
        let (Some(below), Some(above)) = (literal.checked_sub(1), literal.checked_add(1)) else {
            return Vec::new();
        };
        let Some(source) = self.int_cast_operand(cast_expr) else {
            return Vec::new();
        };
        let mut guards = vec![
            Guard::IntGt {
                path: source.path.clone(),
                bound: below,
            },
            Guard::IntLt {
                path: source.path.clone(),
                bound: above,
            },
        ];
        // A literal `default` substitutes for a raw 0 (numerically empty)
        // BEFORE the comparison: when the fallback misses the literal, a
        // raw 0 no longer satisfies the equality, so exclude it.
        if literal == 0 && source.default_int.is_some_and(|fallback| fallback != 0) {
            guards.push(Guard::NotEq {
                path: source.path,
                value: helm_schema_core::GuardValue::Int(0),
            });
        }
        guards
    }

    /// `not (list "a" "b" | has .Values.x)` is EXACTLY "x differs from
    /// every listed literal" (Sprig `has` is deep equality against each
    /// item), so the negated membership lowers to the `NotEq` conjunction
    /// (cilium's internal-or-external `kvstoreMode` check).
    fn negated_membership_sound_subset(&self, expr: &TemplateExpr) -> Vec<Guard> {
        let TemplateExpr::Call { function, args } = expr.deparen() else {
            return Vec::new();
        };
        let [inner] = args.as_slice() else {
            return Vec::new();
        };
        if function != "not" {
            return Vec::new();
        }
        let (subject, list_args) = match inner.deparen() {
            TemplateExpr::Call { function, args } if function == "has" => {
                let [subject, list] = args.as_slice() else {
                    return Vec::new();
                };
                (subject, list)
            }
            TemplateExpr::Pipeline(stages) => match stages.as_slice() {
                [list, has] => match (list.deparen(), has.deparen()) {
                    (
                        list @ TemplateExpr::Call { function, .. },
                        TemplateExpr::Call {
                            function: has_name,
                            args: has_args,
                        },
                    ) if matches!(function.as_str(), "list" | "tuple")
                        && has_name == "has"
                        && has_args.len() == 1 =>
                    {
                        let Some(subject) = has_args.first() else {
                            return Vec::new();
                        };
                        (subject, list)
                    }
                    _ => return Vec::new(),
                },
                _ => return Vec::new(),
            },
            _ => return Vec::new(),
        };
        let TemplateExpr::Call {
            function: list_name,
            args: literals,
        } = list_args.deparen()
        else {
            return Vec::new();
        };
        if !matches!(list_name.as_str(), "list" | "tuple") || literals.is_empty() {
            return Vec::new();
        }
        let Some(path) = self.single_resolved_values_path_expr(subject) else {
            return Vec::new();
        };
        let mut guards = Vec::new();
        for literal in literals {
            let value = match literal.deparen() {
                TemplateExpr::Literal(Literal::String(text) | Literal::RawString(text)) => {
                    helm_schema_core::GuardValue::string(text.clone())
                }
                TemplateExpr::Literal(Literal::Int(value)) => {
                    helm_schema_core::GuardValue::Int(*value)
                }
                _ => return Vec::new(),
            };
            guards.push(Guard::NotEq {
                path: path.clone(),
                value,
            });
        }
        guards
    }

    /// `semverCompare "<constraint>" .Values.path` with a literal bounded
    /// comparator and a direct values-backed version selector admits an
    /// EXACT strengthening: the comparator lowers to a pattern matching
    /// precisely the version strings that satisfy it, so a fail-arm keyed
    /// on the pattern fires exactly where the guard held (airflow
    /// `semverCompare "<3.0.0" .Values.airflowVersion`). The pipeline form
    /// admits the digest-strip / v-trim transform chain — cilium's
    /// `regexReplaceAll "@.*$" TAG "" | trimPrefix "v" | semverCompare
    /// "<0.9.0"` — whose edge wraps compose the constraint language
    /// EXACTLY (see [`Self::semver_transformed_operand`]); any other
    /// transformed operand no longer carries the path's own text and
    /// abstains, as does a fallback chain selecting other sources.
    fn semver_comparison_sound_subset(&self, expr: &TemplateExpr) -> Vec<Guard> {
        let (constraint, path, escapes) = match expr.deparen() {
            TemplateExpr::Call { function, args } if function == "semverCompare" => {
                let [constraint, subject] = args.as_slice() else {
                    return Vec::new();
                };
                let TemplateExpr::Literal(Literal::String(constraint)) = constraint.deparen()
                else {
                    return Vec::new();
                };
                if !matches!(
                    subject.deparen(),
                    TemplateExpr::Field(_) | TemplateExpr::Selector { .. }
                ) {
                    return Vec::new();
                }
                let Some(path) = self.single_resolved_values_path_expr(subject) else {
                    return Vec::new();
                };
                (constraint, path, BTreeSet::new())
            }
            TemplateExpr::Pipeline(stages) => {
                let Some((last, transforms)) = stages.split_last() else {
                    return Vec::new();
                };
                let TemplateExpr::Call { function, args } = last.deparen() else {
                    return Vec::new();
                };
                let [constraint] = args.as_slice() else {
                    return Vec::new();
                };
                if function != "semverCompare" {
                    return Vec::new();
                }
                let TemplateExpr::Literal(Literal::String(constraint)) = constraint.deparen()
                else {
                    return Vec::new();
                };
                let Some((path, escapes)) = self.semver_transformed_operand(transforms) else {
                    return Vec::new();
                };
                (constraint, path, escapes)
            }
            _ => return Vec::new(),
        };
        let Some(pattern) = helm_schema_ast::semver_constraint_match_pattern(constraint) else {
            return Vec::new();
        };
        vec![Guard::MatchesPattern {
            path,
            pattern: crate::helper_meta::pattern_with_lexical_escapes(&pattern, &escapes),
            templated: false,
        }]
    }

    /// The `(path, escapes)` of a transformed `semverCompare` version
    /// operand whose chain composes the constraint language EXACTLY — the
    /// requirement for a fail-position guard, where a mere widening would
    /// reject renders that succeed. Admitted stages: an innermost
    /// `regexReplaceAll "TOKEN.*$" SELECTOR ""` erasure whose literal
    /// token holds a character no semver spelling contains (the constraint
    /// language is token-free, so the cut tail is the exact preimage), and
    /// at most one piped `trimPrefix "v"` (the constraint pattern is
    /// `v?`-normalized, so a valid string wearing the prefix trims to a
    /// valid string — the wrap loses nothing). Anything else abstains.
    fn semver_transformed_operand(
        &self,
        transforms: &[TemplateExpr],
    ) -> Option<(String, BTreeSet<crate::helper_meta::LexicalEscape>)> {
        use crate::helper_meta::LexicalEscape;
        let (first, rest) = transforms.split_first()?;
        let mut escapes = BTreeSet::new();
        for stage in rest {
            let TemplateExpr::Call { function, args } = stage.deparen() else {
                return None;
            };
            let [token] = args.as_slice() else {
                return None;
            };
            if function != "trimPrefix" {
                return None;
            }
            let token = literal_string(token)?;
            if token != "v" || !escapes.insert(LexicalEscape::TrimPrefix(token.to_string())) {
                return None;
            }
        }
        let subject = match first.deparen() {
            TemplateExpr::Call { function, args }
                if matches!(
                    function.as_str(),
                    "regexReplaceAll"
                        | "mustRegexReplaceAll"
                        | "regexReplaceAllLiteral"
                        | "mustRegexReplaceAllLiteral"
                ) && args.len() == 3 =>
            {
                let [pattern, subject, replacement] = args.as_slice() else {
                    return None;
                };
                let pattern = literal_string(pattern)?;
                let replacement = literal_string(replacement)?;
                let token = pattern.strip_suffix(".*$")?;
                let token_is_regex_literal = !token.is_empty()
                    && token.chars().all(|character| {
                        !matches!(
                            character,
                            '\\' | '.'
                                | '^'
                                | '$'
                                | '|'
                                | '?'
                                | '*'
                                | '+'
                                | '('
                                | ')'
                                | '['
                                | ']'
                                | '{'
                                | '}'
                        )
                    });
                let token_outside_semver = token.chars().any(|character| {
                    !character.is_ascii_alphanumeric() && !matches!(character, '.' | '-' | '+')
                });
                if !replacement.is_empty() || !token_is_regex_literal || !token_outside_semver {
                    return None;
                }
                escapes.insert(LexicalEscape::CutAtToken(token.to_string()));
                subject
            }
            _ => first,
        };
        if !matches!(
            subject.deparen(),
            TemplateExpr::Field(_) | TemplateExpr::Selector { .. }
        ) {
            return None;
        }
        let path = self.single_resolved_values_path_expr(subject)?;
        (!escapes.is_empty()).then_some((path, escapes))
    }

    /// `gt (int64 x) N` / `gt (int x) N` and the mirrored below-bound forms
    /// (`lt (int x) N`, either operand order flipped) with an integer
    /// literal bound admit a bounded sound strengthening: a RAW JSON
    /// integer beyond the bound always satisfies the coercing comparison,
    /// so a fail-arm keyed on the strengthened guard keeps firing there
    /// instead of abstaining wholesale (redis `gt (int64 .Values.
    /// master.count) 0`, jenkins' `$replicas` domain). The cast may sit
    /// behind a bound local.
    ///
    /// The inclusive comparators normalize into the strict guards with a
    /// shifted bound — `ge (int x) N` ⇔ `gt (int x) (N-1)` over int64 —
    /// abstaining when the shift overflows (cilium's `ge (int
    /// .Values.cluster.id) 128` ENI window).
    fn int_cast_comparison_sound_subset(&self, expr: &TemplateExpr) -> Vec<Guard> {
        self.int_cast_comparison_region_subset(expr, false)
    }

    fn int_cast_comparison_region_subset(&self, expr: &TemplateExpr, negated: bool) -> Vec<Guard> {
        let TemplateExpr::Call { function, args } = expr.deparen() else {
            return Vec::new();
        };
        let [left, right] = args.as_slice() else {
            return Vec::new();
        };
        let form = match (function.as_str(), left.deparen(), right.deparen()) {
            ("gt", cast, TemplateExpr::Literal(Literal::Int(bound)))
            | ("lt", TemplateExpr::Literal(Literal::Int(bound)), cast) => {
                Some((cast, *bound, true))
            }
            ("lt", cast, TemplateExpr::Literal(Literal::Int(bound)))
            | ("gt", TemplateExpr::Literal(Literal::Int(bound)), cast) => {
                Some((cast, *bound, false))
            }
            ("ge", cast, TemplateExpr::Literal(Literal::Int(bound)))
            | ("le", TemplateExpr::Literal(Literal::Int(bound)), cast) => {
                bound.checked_sub(1).map(|bound| (cast, bound, true))
            }
            ("le", cast, TemplateExpr::Literal(Literal::Int(bound)))
            | ("ge", TemplateExpr::Literal(Literal::Int(bound)), cast) => {
                bound.checked_add(1).map(|bound| (cast, bound, false))
            }
            _ => None,
        };
        let Some((cast_expr, bound, greater)) = form else {
            return Vec::new();
        };
        // Negation flips the region: ¬(x > N) ⇔ x < N+1 over int64. The
        // flipped guard feeds the same zero/fallback reasoning below — the
        // claim is still plain region membership of the coerced value.
        let (bound, greater) = if negated {
            let flipped = if greater {
                bound.checked_add(1)
            } else {
                bound.checked_sub(1)
            };
            match flipped {
                Some(bound) => (bound, !greater),
                None => return Vec::new(),
            }
        } else {
            (bound, greater)
        };
        let Some(source) = self.int_cast_operand(cast_expr) else {
            return Vec::new();
        };
        let mut guards = vec![if greater {
            Guard::IntGt {
                path: source.path.clone(),
                bound,
            }
        } else {
            Guard::IntLt {
                path: source.path.clone(),
                bound,
            }
        }];
        // A literal `default` substitutes for a raw 0 (numerically empty)
        // BEFORE the comparison: when 0 itself would satisfy the claim but
        // the substituted fallback does not, exclude 0 from the claim.
        let zero_claims = if greater { 0 > bound } else { 0 < bound };
        let fallback_escapes = source.default_int.is_some_and(|fallback| {
            !(if greater {
                fallback > bound
            } else {
                fallback < bound
            })
        });
        if zero_claims && fallback_escapes {
            guards.push(Guard::NotEq {
                path: source.path,
                value: helm_schema_core::GuardValue::Int(0),
            });
        }
        guards
    }

    /// The int-cast provenance behind a comparison operand: the inline
    /// `int X` / `int (default L X)` call over one direct values selector,
    /// or a local bound to exactly that shape. Any other subject transform
    /// breaks the "a raw JSON integer at the path reaches the comparison
    /// unchanged" argument the raw-integer subsets rely on.
    /// `semverCompare "<constraint>" SUBJECT` where SUBJECT is the policy
    /// Kubernetes version, optionally shadowed by a values-path override
    /// (`default .Capabilities.KubeVersion.X .Values.kubeTargetVersionOverride`,
    /// directly or through a bound local). The constraint's exact version
    /// language comes from the semver pattern encoder; the policy arm
    /// evaluates it against the configured version, and the override arm
    /// tests the raw override text — both exact, so the negated form stays
    /// faithful.
    fn semver_capabilities_predicate(&self, args: &[TemplateExpr]) -> Option<Predicate> {
        let [constraint_expr, subject] = args else {
            return None;
        };
        let TemplateExpr::Literal(Literal::String(constraint) | Literal::RawString(constraint)) =
            constraint_expr.deparen()
        else {
            return None;
        };
        let source = self.kube_version_subject(subject)?;
        let policy = self.fragment_context.analysis_db.kubernetes_version()?;
        let pattern = helm_schema_ast::semver_constraint_match_pattern(constraint)?;
        let regex = regex::Regex::new(&pattern).ok()?;
        let policy_matches = regex.is_match(policy);
        Some(match source.override_path {
            None => bool_predicate(policy_matches),
            Some(path) => {
                let truthy = Predicate::truthy_path(path.clone());
                let matches = Predicate::from(Guard::MatchesPattern {
                    path,
                    pattern,
                    templated: false,
                });
                if policy_matches {
                    // A falsy override renders the (satisfying) policy
                    // version; a truthy override must satisfy on its own.
                    predicate_any(vec![
                        truthy.negated(),
                        Predicate::all(vec![truthy, matches]),
                    ])
                } else {
                    Predicate::all(vec![truthy, matches])
                }
            }
        })
    }

    fn kube_version_subject(
        &self,
        expr: &TemplateExpr,
    ) -> Option<crate::symbolic_local_state::KubeVersionSource> {
        if let TemplateExpr::Variable(name) = expr.deparen() {
            return self
                .kube_version_bindings
                .get(name.trim_start_matches('$'))
                .cloned();
        }
        self.kube_version_operand(expr)
    }

    /// The Kubernetes-version identity of an expression: a bare
    /// `.Capabilities.KubeVersion.Version|GitVersion` selector, or a
    /// `default` of that fallback with a DIRECT values-path override (a
    /// transformed override no longer carries the path's raw text).
    pub(crate) fn kube_version_operand(
        &self,
        expr: &TemplateExpr,
    ) -> Option<crate::symbolic_local_state::KubeVersionSource> {
        let expr = expr.deparen();
        if capabilities_kube_version_selector(expr) {
            return Some(crate::symbolic_local_state::KubeVersionSource {
                override_path: None,
            });
        }
        let TemplateExpr::Call { function, args } = expr else {
            return None;
        };
        if function != "default" {
            return None;
        }
        let [fallback, subject] = args.as_slice() else {
            return None;
        };
        if !capabilities_kube_version_selector(fallback.deparen()) {
            return None;
        }
        if !matches!(
            subject.deparen(),
            TemplateExpr::Field(_) | TemplateExpr::Selector { .. }
        ) {
            return None;
        }
        let path = self.single_resolved_values_path_expr(subject)?;
        Some(crate::symbolic_local_state::KubeVersionSource {
            override_path: Some(path),
        })
    }

    pub(crate) fn int_cast_operand(
        &self,
        expr: &TemplateExpr,
    ) -> Option<crate::symbolic_local_state::IntCastSource> {
        if let TemplateExpr::Variable(name) = expr.deparen() {
            return self
                .int_cast_bindings
                .get(name)
                .or_else(|| self.int_cast_bindings.get(name.trim_start_matches('$')))
                .cloned();
        }
        let TemplateExpr::Call { function, args } = expr.deparen() else {
            return None;
        };
        let [operand] = args.as_slice() else {
            return None;
        };
        if !matches!(function.as_str(), "int" | "int64") {
            return None;
        }
        let (subject, default_int) = match operand.deparen() {
            TemplateExpr::Call { function, args } if function == "default" => {
                let [fallback, subject] = args.as_slice() else {
                    return None;
                };
                let TemplateExpr::Literal(Literal::Int(fallback)) = fallback.deparen() else {
                    return None;
                };
                (subject, Some(*fallback))
            }
            _ => (operand, None),
        };
        if !matches!(
            subject.deparen(),
            TemplateExpr::Field(_) | TemplateExpr::Selector { .. }
        ) {
            return None;
        }
        let path = self.single_resolved_values_path_expr(subject)?;
        Some(crate::symbolic_local_state::IntCastSource { path, default_int })
    }

    fn single_truthy_predicate(&self, expr: &TemplateExpr) -> Option<Predicate> {
        if let TemplateExpr::Variable(name) = expr.deparen()
            && let Some(predicate) = self.template_truthy_reductions.get(name).or_else(|| {
                self.template_truthy_reductions
                    .get(name.trim_start_matches('$'))
            })
        {
            return Some(predicate.clone());
        }
        let mut paths = self.paths_for_expr(expr).into_iter();
        let path = paths.next()?;
        paths.next().is_none().then(|| Predicate::truthy_path(path))
    }

    fn condition_has_unrepresentable_values_comparison_expr(&self, expr: &TemplateExpr) -> bool {
        let TemplateExpr::Call { function, args } = expr.deparen() else {
            return false;
        };
        match function.as_str() {
            "eq" | "ne" => self.comparison_has_unrepresentable_values(args),
            "typeIs" => {
                args.iter()
                    .any(|arg| self.expr_needs_context_value_resolution(arg))
                    && self.type_is_predicate(args).is_none()
            }
            _ => false,
        }
    }

    #[expect(
        clippy::too_many_lines,
        reason = "keeping this semantic operation together makes its state transitions easier to audit"
    )]
    fn value_comparison_predicate(
        &self,
        args: &[TemplateExpr],
        negated: bool,
    ) -> Option<Predicate> {
        let [left, right] = args else {
            return None;
        };
        // `eq (typeOf .Values.x) "string"` (also through a bound local
        // `$tp := typeOf .Values.x`) is a TYPE TEST on the path, never a
        // value equality.
        if let Some(predicate) = self.type_descriptor_comparison(left, right, negated) {
            return Some(predicate);
        }
        // `eq $key "name"` over a destructured range key selects exactly the
        // member with that key (prometheus's serverFiles dispatch).
        if let Some(predicate) = self.range_key_equals_predicate(left, right, negated) {
            return Some(predicate);
        }
        // A root-context field assigned across a COMPLETE if/else chain
        // compares through its joined value dispatch: the equality selects
        // exactly the arms assigning the compared literal (vault's
        // `eq .mode "ha"` / `ne .mode "external"` gates). The arm conditions
        // are mutually exclusive and total, so the negated form is the
        // exact complement.
        if let Some(predicate) = self.root_field_dispatch_predicate(left, right, negated) {
            return Some(predicate);
        }
        // Only a DIRECT selector operand claims a value equality: seeing
        // through a call (`eq (typeOf .Values.x) "string"`) would compare
        // the call's OUTPUT, not the path's value. Two call shapes are
        // admitted: literal-key `index` navigation — its output IS the raw
        // member value (nil when absent), so the equality binds the member
        // path exactly (cilium's `ne (index .Values.extraConfig
        // "allow-unsafe-policy-skb-usage") "true"` gate) — and `toString`
        // over a selector, whose output is the `%v` rendering the preimage
        // projection below decodes exactly (cilium validate.yaml's
        // `eq (toString .Values.kubeProxyReplacement) "disabled"`).
        let direct_selector = |expr: &TemplateExpr| match expr.deparen() {
            TemplateExpr::Field(_) | TemplateExpr::Selector { .. } => true,
            TemplateExpr::Variable(name) => !self
                .typeof_bindings
                .contains_key(name.trim_start_matches('$')),
            TemplateExpr::Call { function, args } if function == "index" => {
                args.split_first().is_some_and(|(base, keys)| {
                    !keys.is_empty()
                        && matches!(
                            base.deparen(),
                            TemplateExpr::Field(_) | TemplateExpr::Selector { .. }
                        )
                        && keys.iter().all(|key| {
                            matches!(
                                key.deparen(),
                                TemplateExpr::Literal(Literal::String(_) | Literal::RawString(_))
                            )
                        })
                })
            }
            expr => is_tostring_selector(expr),
        };
        // A `toString`-wrapped selector compares the rendering of the inner
        // path's value; resolve the paths from the operand itself.
        // Literal-key `index` navigation compares the MEMBER value only; the
        // evaluator's influence set also carries the parent map, which is
        // not the compared value.
        let subject_paths = |expr: &TemplateExpr| {
            let expr = tostring_wrapped_subject(expr).unwrap_or(expr);
            if let TemplateExpr::Call { function, args } = expr.deparen()
                && function == "index"
                && let Some((base_expr, keys)) = args.split_first()
                && let Some(base) = self.single_resolved_values_path_expr(base_expr)
            {
                let mut path = base;
                for key in keys {
                    match key.deparen() {
                        TemplateExpr::Literal(Literal::String(key) | Literal::RawString(key)) => {
                            path = helm_schema_core::append_value_path(&path, key);
                        }
                        _ => return self.paths_for_expr(expr),
                    }
                }
                return std::collections::BTreeSet::from([path]);
            }
            self.paths_for_expr(expr)
        };
        let (value, paths) = match (guard_value_literal(left), guard_value_literal(right)) {
            (Some(value), None) if direct_selector(right) => (value, subject_paths(right)),
            (None, Some(value)) if direct_selector(left) => (value, subject_paths(left)),
            _ => {
                // Two statically known scalars compare as a constant:
                // `eq (len $secret.path) (add1 $index)` selects the last
                // element of an exactly unrolled iteration.
                if let (Some(left_value), Some(right_value)) =
                    (self.constant_scalar(left), self.constant_scalar(right))
                {
                    return Some(bool_predicate((left_value == right_value) != negated));
                }
                // `eq (default D X) V` over a literal fallback D compares X
                // with its Helm-falsy states substituted by D: with V == D
                // the guard also holds for every falsy X; a truthy V ≠ D
                // binds X == V exactly (a falsy X renders D ≠ V); a falsy
                // V ≠ D never holds (any X equal to V would itself be falsy
                // and render D instead). oauth2-proxy's
                // `eq (default "" .Values.…clientType) "standalone"` caller
                // gate rides this shape.
                let defaulted = match (guard_value_literal(left), guard_value_literal(right)) {
                    (Some(value), None) => default_call_operand(right)
                        .map(|(fallback, subject)| (value, fallback, subject)),
                    (None, Some(value)) => default_call_operand(left)
                        .map(|(fallback, subject)| (value, fallback, subject)),
                    _ => None,
                };
                if let Some((value, fallback, subject)) = defaulted
                    && direct_selector(subject)
                {
                    let paths = subject_paths(subject);
                    if !paths.is_empty() {
                        let predicate = if value == fallback {
                            Predicate::all(
                                paths
                                    .iter()
                                    .map(|path| {
                                        predicate_any(vec![
                                            Predicate::from(Guard::Eq {
                                                path: path.clone(),
                                                value: value.clone(),
                                            }),
                                            Predicate::truthy_path(path.clone()).negated(),
                                        ])
                                    })
                                    .collect(),
                            )
                        } else if guard_value_is_truthy(&value) {
                            Predicate::all(
                                paths
                                    .iter()
                                    .map(|path| {
                                        Predicate::from(Guard::Eq {
                                            path: path.clone(),
                                            value: value.clone(),
                                        })
                                    })
                                    .collect(),
                            )
                        } else {
                            bool_predicate(false)
                        };
                        return Some(if negated {
                            predicate.negated()
                        } else {
                            predicate
                        });
                    }
                }
                return self.helper_literal_dispatch_predicate(left, right, negated);
            }
        };
        let subject = if guard_value_literal(left).is_some() {
            right
        } else {
            left
        };
        let subject_meta_for = |path: &str| {
            let TemplateExpr::Variable(name) = subject.deparen() else {
                return None;
            };
            self.template_output_meta
                .get(name)
                .or_else(|| self.template_output_meta.get(name.trim_start_matches('$')))
                .and_then(|by_path| by_path.get(path))
        };
        let comparison_for = |path: String| {
            // Equality over a total stringification compares the DERIVED
            // text, so a string literal binds the raw path through its
            // `toString` preimage: every raw value that renders the same
            // text stays inside the equality (cilium's
            // `ne $kubeProxyReplacement "true"` chain must keep a raw
            // Boolean `true` beside the string spelling). Serialized or
            // include-derived text has a different (or unknowable) image
            // and keeps the literal alone.
            let stringified = is_tostring_selector(subject)
                || subject_meta_for(&path).is_some_and(|meta| meta.stringified);
            let candidates = match &value {
                GuardValue::String(text) if stringified => {
                    let mut candidates = stringified_equality_preimage(text);
                    // A recorded coalesce rescue substitutes the fallback
                    // exactly while the stringification renders Helm-empty,
                    // so an equality against the fallback literal also
                    // admits the empty spellings (cilium's
                    // `ne $kubeProxyReplacement "false"` chain keeps ""
                    // and null renderable).
                    if let Some(rescue) =
                        subject_meta_for(&path).and_then(|meta| meta.empty_rescue.as_ref())
                        && rescue.fallback == *text
                    {
                        for spelling in &rescue.spellings {
                            if !candidates.contains(spelling) {
                                candidates.push(spelling.clone());
                            }
                        }
                    }
                    candidates
                }
                other => vec![other.clone()],
            };
            let comparisons = candidates
                .into_iter()
                .map(|candidate| {
                    if negated {
                        Predicate::from(Guard::NotEq {
                            path: path.clone(),
                            value: candidate,
                        })
                    } else {
                        Predicate::from(Guard::Eq {
                            path: path.clone(),
                            value: candidate,
                        })
                    }
                })
                .collect::<Vec<_>>();
            // `ne` holds only when the raw value misses EVERY preimage
            // member; `eq` when it hits any one of them.
            if negated {
                Predicate::all(comparisons)
            } else {
                predicate_any(comparisons)
            }
        };
        if let TemplateExpr::Variable(name) = subject.deparen() {
            let meta = self
                .template_output_meta
                .get(name)
                .or_else(|| self.template_output_meta.get(name.trim_start_matches('$')));
            // A binding qualified by lexical escape tokens is not the raw
            // value for every input (a replace/split chain rewrote some
            // strings): an equality on it cannot lower to a raw-path
            // guard.
            if meta.is_some_and(|meta| {
                meta.values()
                    .any(|candidate| !candidate.lexical_escapes.is_empty())
            }) {
                return None;
            }
            if let Some(meta) = meta.filter(|meta| {
                meta.values()
                    .any(|candidate| !candidate.predicates.is_empty())
            }) {
                let mut alternatives = Vec::new();
                for path in &paths {
                    let comparison = comparison_for(path.clone());
                    match meta.get(path) {
                        Some(candidate) if !candidate.predicates.is_empty() => {
                            for branch in &candidate.predicates {
                                let mut conjuncts = branch.iter().cloned().collect::<Vec<_>>();
                                conjuncts.push(comparison.clone());
                                alternatives.push(Predicate::all(conjuncts));
                            }
                            // A recorded literal `default` fallback IS the
                            // binding's value on every Helm-falsy input, so
                            // the comparison decodes exactly there too:
                            // `eq $mode FALLBACK` also holds where the path
                            // is falsy, and `ne $mode OTHER` does likewise.
                            // Bounded to the pure `PATH | default LIT`
                            // binding (its single truthy-path branch, no
                            // value transform), where the falsy-arm
                            // condition is exactly `¬truthy(path)`.
                            if let Some(fallback) = &candidate.default_fallback
                                && !candidate.stringified
                                && !candidate.shape_erased
                                && !candidate.derived_text
                                && !candidate.json_serialized
                                && (fallback == &value) != negated
                                && candidate.predicates
                                    == BTreeSet::from([BTreeSet::from([Predicate::truthy_path(
                                        path.clone(),
                                    )])])
                            {
                                alternatives.push(Predicate::truthy_path(path.clone()).negated());
                            }
                        }
                        _ => alternatives.push(comparison),
                    }
                }
                return Some(match alternatives.as_slice() {
                    [only] => only.clone(),
                    _ => Predicate::Or(alternatives),
                });
            }
        }
        let predicates = paths
            .iter()
            .cloned()
            .map(comparison_for)
            .collect::<Vec<_>>();
        (!predicates.is_empty()).then(|| Predicate::all(predicates))
    }

    /// The values paths (with any binding-time meta) a `typeOf`/`kindOf`
    /// descriptor expression describes: a direct call over a selector or
    /// bound local, or a local bound to such a call
    /// (`$tp := typeOf .Values.x`).
    fn type_descriptor_sources(
        &self,
        expr: &TemplateExpr,
    ) -> Option<std::collections::BTreeMap<String, crate::helper_meta::HelperOutputMeta>> {
        match expr.deparen() {
            TemplateExpr::Call { function, args }
                if helm_schema_ast::type_descriptor_call_subject(function, args).is_some() =>
            {
                // Selectors and bound locals (a range's value variable,
                // a `$x := .Values.y` binding) both describe a single
                // resolvable path.
                let subject =
                    helm_schema_ast::type_descriptor_call_subject(function, args)?.deparen();
                let subject = matches!(
                    subject,
                    TemplateExpr::Field(_)
                        | TemplateExpr::Selector { .. }
                        | TemplateExpr::Variable(_)
                )
                .then_some(subject)?;
                let paths = self.paths_for_expr(subject);
                if paths.is_empty() {
                    return None;
                }
                let local_meta = match subject {
                    TemplateExpr::Variable(name) => {
                        self.template_output_meta.get(name.trim_start_matches('$'))
                    }
                    _ => None,
                };
                Some(
                    paths
                        .into_iter()
                        .map(|path| {
                            let meta = local_meta
                                .and_then(|meta| meta.get(&path))
                                .cloned()
                                .unwrap_or_default();
                            (path, meta)
                        })
                        .collect(),
                )
            }
            TemplateExpr::Variable(name) => self
                .typeof_bindings
                .get(name.trim_start_matches('$'))
                .cloned(),
            _ => None,
        }
    }

    /// `regexMatch pat (typeOf x)` tests the FINITE set of type spellings a
    /// chart value can print, so the pattern lowers to the type alternatives
    /// whose every spelling matches (sealed-secrets' `regexMatch "64$"
    /// (typeOf .Values.pdb.minAvailable)` emits the field only for numeric
    /// kinds). A kind with mixed spelling verdicts is provenance-dependent
    /// (file-decoded `float64` vs `--set` `int64`), so it abstains rather
    /// than guessing either way.
    fn type_descriptor_regex_predicate(
        &self,
        pattern: &str,
        subject: &TemplateExpr,
    ) -> Option<Predicate> {
        let sources = self.type_descriptor_sources(subject)?;
        let regex = regex::Regex::new(pattern).ok()?;
        let mut matched_types = Vec::new();
        for schema_type in ["array", "boolean", "integer", "number", "object", "string"] {
            let spellings = helm_schema_ast::go_type_descriptor_spellings(schema_type);
            let matches = spellings
                .iter()
                .filter(|spelling| regex.is_match(spelling))
                .count();
            if matches == spellings.len() {
                matched_types.push(schema_type);
            } else if matches != 0 {
                return None;
            }
        }
        // `typeOf nil` prints `<nil>` and `kindOf nil` prints `invalid`.
        let null_spellings = ["<nil>", "invalid"];
        let null_matches = null_spellings
            .iter()
            .filter(|spelling| regex.is_match(spelling))
            .count();
        if null_matches != 0 && null_matches != null_spellings.len() {
            return None;
        }
        if matched_types.is_empty() && null_matches == 0 {
            return None;
        }
        let mut alternatives = Vec::new();
        for (path, meta) in sources {
            let mut kind_alternatives: Vec<Predicate> = matched_types
                .iter()
                .map(|schema_type| {
                    Predicate::from(Guard::TypeIs {
                        path: path.clone(),
                        schema_type: (*schema_type).to_string(),
                    })
                })
                .collect();
            if null_matches != 0 {
                kind_alternatives.push(invalid_kind_predicate(path.clone()));
            }
            let type_predicate = predicate_any(kind_alternatives);
            if meta.predicates.is_empty() {
                alternatives.push(type_predicate);
            } else {
                alternatives.extend(meta.predicates.into_iter().map(|branch| {
                    let mut conjunction = branch.into_iter().collect::<Vec<_>>();
                    conjunction.push(type_predicate.clone());
                    Predicate::all(conjunction)
                }));
            }
        }
        match alternatives.as_slice() {
            [] => None,
            [predicate] => Some(predicate.clone()),
            _ => Some(Predicate::Or(alternatives)),
        }
    }

    /// A `typeOf`/`kindOf` comparison against a string literal, either
    /// directly (`eq (typeOf .Values.x) "string"`) or through a bound local
    /// (`$tp := typeOf .Values.x` then `eq $tp "string"`). Lowers to a
    /// [`Guard::TypeIs`] on the described path.
    fn type_descriptor_comparison(
        &self,
        left: &TemplateExpr,
        right: &TemplateExpr,
        negated: bool,
    ) -> Option<Predicate> {
        fn type_literal(expr: &TemplateExpr) -> Option<&str> {
            match expr.deparen() {
                TemplateExpr::Literal(Literal::String(name) | Literal::RawString(name)) => {
                    Some(name.as_str())
                }
                _ => None,
            }
        }
        let (sources, type_name) = match (
            self.type_descriptor_sources(left),
            self.type_descriptor_sources(right),
        ) {
            (Some(sources), None) => (sources, type_literal(right)?),
            (None, Some(sources)) => (sources, type_literal(left)?),
            _ => return None,
        };
        let schema_type = helm_schema_ast::go_type_schema_type(type_name);
        if type_name != "invalid" && schema_type.is_none() {
            return None;
        }
        let mut alternatives = Vec::new();
        for (path, meta) in sources {
            let type_predicate = match schema_type {
                Some(schema_type) => Predicate::from(Guard::TypeIs {
                    path,
                    schema_type: schema_type.to_string(),
                }),
                None => invalid_kind_predicate(path),
            };
            let type_predicate = if negated {
                type_predicate.negated()
            } else {
                type_predicate
            };
            if meta.predicates.is_empty() {
                alternatives.push(type_predicate);
            } else {
                alternatives.extend(meta.predicates.into_iter().map(|branch| {
                    let mut conjunction = branch.into_iter().collect::<Vec<_>>();
                    conjunction.push(type_predicate.clone());
                    Predicate::all(conjunction)
                }));
            }
        }
        match alternatives.as_slice() {
            [] => None,
            [predicate] => Some(predicate.clone()),
            _ => Some(Predicate::Or(alternatives)),
        }
    }

    fn comparison_has_unrepresentable_values(&self, args: &[TemplateExpr]) -> bool {
        if !args
            .iter()
            .any(|arg| self.expr_needs_context_value_resolution(arg))
        {
            return false;
        }
        let [left, right] = args else {
            return true;
        };
        !matches!(
            (guard_value_literal(left), guard_value_literal(right)),
            (Some(_), None) | (None, Some(_))
        )
    }
}

fn invalid_kind_predicate(path: String) -> Predicate {
    Predicate::Or(vec![
        Predicate::from(Guard::Absent { path: path.clone() }),
        Predicate::from(Guard::Eq {
            path,
            value: GuardValue::Null,
        }),
    ])
}

/// The raw values whose Go `toString` rendering equals `text`, for an
/// equality whose subject is a total stringification of the path.
///
/// The string itself always renders itself. Beyond it, `%v` prints Booleans
/// as `true`/`false`, nil as `<nil>`, and numbers in fixed decimal notation —
/// but float64 switches to exponent form at 1e6 (`1e+06`), so only spellings
/// below that magnitude cover draft-07's single number kind exactly (an
/// `enum` integer already accepts the numerically equal float). Larger or
/// non-canonical spellings keep the string alone rather than claim a
/// preimage that splits the int and float channels.
fn stringified_equality_preimage(text: &str) -> Vec<GuardValue> {
    let mut values = vec![GuardValue::string(text)];
    match text {
        "true" => values.push(GuardValue::Bool(true)),
        "false" => values.push(GuardValue::Bool(false)),
        "<nil>" => values.push(GuardValue::Null),
        _ => {
            if let Ok(value) = text.parse::<i64>()
                && value.to_string() == text
                && (-1_000_000..1_000_000).contains(&value)
            {
                values.push(GuardValue::Int(value));
            }
        }
    }
    values
}

pub(crate) fn predicate_any(predicates: Vec<Predicate>) -> Predicate {
    if predicates
        .iter()
        .any(|predicate| matches!(predicate, Predicate::True))
    {
        return Predicate::True;
    }
    let mut predicates = predicates
        .into_iter()
        .filter(|predicate| !matches!(predicate, Predicate::False))
        .collect::<Vec<_>>();
    match predicates.len() {
        0 => Predicate::False,
        1 => predicates.remove(0),
        _ => Predicate::Or(predicates),
    }
}

fn literal_is_truthy(literal: &Literal) -> bool {
    match literal {
        Literal::Bool(value) => *value,
        Literal::Int(value) => *value != 0,
        Literal::Float(value) => *value != 0.0,
        Literal::String(value) | Literal::RawString(value) => !value.is_empty(),
        Literal::Nil => false,
    }
}

fn escape_regex_literal(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len());
    for character in value.chars() {
        if matches!(
            character,
            '.' | '+' | '*' | '?' | '(' | ')' | '|' | '[' | ']' | '{' | '}' | '^' | '$' | '\\'
        ) {
            escaped.push('\\');
        }
        escaped.push(character);
    }
    escaped
}

/// Helm truthiness of an ordered merge: nonempty exactly when some layer
/// is. A nonempty literal layer decides the whole merge; identity layers
/// contribute their own truthiness; any other layer kind abstains. A
/// WILDCARD layer path also abstains: the ranged capture machinery owns
/// member-quantified encodings (airflow's per-set labels under the merged
/// worker context), and a disjunction naming `p.*` members would drop at
/// guard lowering instead of riding that encoding.
fn merged_layers_truthy_predicate(layers: &[AbstractValue]) -> Option<Predicate> {
    let mut arms = Vec::new();
    for layer in layers {
        match layer {
            AbstractValue::Dict(entries) => {
                if !entries.is_empty() {
                    return Some(Predicate::True);
                }
            }
            AbstractValue::ValuesPath(path) | AbstractValue::JsonDecodedPath(path) => {
                if path.split('.').any(|segment| segment == "*") {
                    return None;
                }
                arms.push(Predicate::truthy_path(path));
            }
            // A nil-scrubbed identity over-approximates: an all-nil map is
            // input-truthy but scrubs to empty. The wider condition only
            // fires arms whose member typing is null-relaxed, so the delta
            // stays in the accept direction.
            AbstractValue::OutputPath(path, meta) if meta.nil_scrubbed && !path.is_empty() => {
                if path.split('.').any(|segment| segment == "*") {
                    return None;
                }
                arms.push(Predicate::truthy_path(path));
            }
            AbstractValue::MergedLayers(nested) => {
                arms.push(merged_layers_truthy_predicate(nested)?);
            }
            _ => return None,
        }
    }
    Some(predicate_any(arms))
}

/// Exact truthiness of a first-truthy selection chain: the disjunction of
/// the candidates' truthiness. Only RAW path identities and statically
/// decided shapes qualify — a transformed candidate's truthiness is not
/// its source path's.
fn first_truthy_truthy_predicate(candidates: &[AbstractValue]) -> Option<Predicate> {
    let mut arms = Vec::new();
    for candidate in candidates {
        match candidate {
            AbstractValue::ValuesPath(path) | AbstractValue::JsonDecodedPath(path) => {
                if path.split('.').any(|segment| segment == "*") {
                    return None;
                }
                arms.push(Predicate::truthy_path(path.clone()));
            }
            other => arms.push(bool_predicate(other.static_truthiness()?)),
        }
    }
    Some(predicate_any(arms))
}

#[expect(
    clippy::too_many_lines,
    reason = "keeping this semantic operation together makes its state transitions easier to audit"
)]
fn value_has_key(value: &AbstractValue, key: &str) -> Option<Predicate> {
    match value {
        AbstractValue::Dict(entries) => Some(bool_predicate(entries.contains_key(key))),
        AbstractValue::Overlay { entries, fallback } => entries
            .contains_key(key)
            .then_some(Predicate::True)
            .or_else(|| value_has_key(fallback, key)),
        AbstractValue::Choice(choices) => {
            // Alternatives must AGREE — including definitely-empty
            // `default list`/`default dict` fallbacks. Skipping the empty
            // alternatives here is tempting for range-item bindings (nats'
            // jsonpatch members ride `.patch | default list`), but the
            // helper walker records member probes at TRUNCATED absolute
            // paths with no range identity, and a decode here feeds those
            // captures into document-level terminal clauses that reject
            // valid documents. The abstention is load-bearing until fail
            // captures carry member identities through helper ranges.
            let mut resolved = choices
                .iter()
                .map(|choice| value_has_key(choice, key))
                .collect::<Option<Vec<_>>>()?;
            resolved.sort();
            resolved.dedup();
            match resolved.as_slice() {
                [predicate] => Some(predicate.clone()),
                _ => None,
            }
        }
        // The selection chain shares the choice's agree-or-abstain rule.
        AbstractValue::FirstTruthy(candidates) => {
            let mut resolved = candidates
                .iter()
                .map(|candidate| value_has_key(candidate, key))
                .collect::<Option<Vec<_>>>()?;
            resolved.sort();
            resolved.dedup();
            match resolved.as_slice() {
                [predicate] => Some(predicate.clone()),
                _ => None,
            }
        }
        // The merged map contains the key exactly when some layer does.
        AbstractValue::MergedLayers(layers) => {
            // Within the layer union, a CHOICE layer's constant-False
            // alternatives are the OR identity: a literal member lacking
            // the key contributes nothing in the iterations that select
            // it (airflow's `concat (list (dict "name" "default"))
            // .Values.workers.celery.sets` per-set layer), so presence
            // reads from the remaining agreeing alternatives.
            let layer_has_key = |layer: &AbstractValue| match layer {
                AbstractValue::Choice(choices) => {
                    let mut resolved = choices
                        .iter()
                        .map(|choice| value_has_key(choice, key))
                        .collect::<Option<Vec<_>>>()?;
                    resolved.retain(|predicate| !matches!(predicate, Predicate::False));
                    resolved.sort();
                    resolved.dedup();
                    match resolved.as_slice() {
                        [] => Some(Predicate::False),
                        [predicate] => Some(predicate.clone()),
                        _ => None,
                    }
                }
                // A selection-chain layer drops a constant-False candidate
                // only where selection can never land on it while the key
                // is present: the LAST candidate is selected only when
                // every prior is falsy, but the agreeing priors are truthy
                // whenever the key is present (`hasKey` implies a nonempty
                // map), and a definitely-falsy candidate is never selected
                // ahead of the tail. KPS' `default (dict) .Values
                // .defaultRules.additionalRuleGroupAnnotations.*` group
                // layer reads presence from the raw path exactly.
                AbstractValue::FirstTruthy(candidates) => {
                    let resolved = candidates
                        .iter()
                        .map(|candidate| value_has_key(candidate, key))
                        .collect::<Option<Vec<_>>>()?;
                    let last = candidates.len().saturating_sub(1);
                    let mut kept = Vec::new();
                    for (index, (candidate, predicate)) in
                        candidates.iter().zip(resolved).enumerate()
                    {
                        if matches!(predicate, Predicate::False)
                            && (index == last || candidate.static_truthiness() == Some(false))
                        {
                            continue;
                        }
                        kept.push(predicate);
                    }
                    kept.sort();
                    kept.dedup();
                    match kept.as_slice() {
                        [] => Some(Predicate::False),
                        [predicate] => Some(predicate.clone()),
                        _ => None,
                    }
                }
                layer => value_has_key(layer, key),
            };
            let mut resolved = layers
                .iter()
                .map(layer_has_key)
                .collect::<Option<Vec<_>>>()?;
            resolved.sort();
            resolved.dedup();
            match resolved.as_slice() {
                [predicate] => Some(predicate.clone()),
                _ => Some(predicate_any(resolved)),
            }
        }
        AbstractValue::ValuesPath(path) | AbstractValue::JsonDecodedPath(path) => Some(
            Predicate::from(Guard::Absent {
                path: helm_schema_core::append_value_path(path, key),
            })
            .negated(),
        ),
        // A nil-scrubbed identity over-approximates presence by the input
        // key's presence: the delta is exactly the nil-ish states, whose
        // member typing the scrubbed layer's arms null-relax, so candidate
        // misselection there only widens.
        AbstractValue::OutputPath(path, meta) if meta.nil_scrubbed && !path.is_empty() => Some(
            Predicate::from(Guard::Absent {
                path: helm_schema_core::append_value_path(path, key),
            })
            .negated(),
        ),
        // A JSON-roundtripped identity keeps map keys exactly, so key
        // presence reads from the raw path (nats' jsonpatch members reach
        // their `hasKey` gates as `service.patch.*` through the
        // toJson/fromJson call boundary). Any value transform, branch
        // condition, or key removal breaks that identity and abstains.
        AbstractValue::OutputPath(path, meta)
            if !path.is_empty()
                && !meta.shape_erased
                && !meta.nil_omitted
                && !meta.stringified
                && !meta.yaml_serialized
                && !meta.derived_text
                && !meta.partial_text
                && meta.merge_layers.is_none()
                && meta.predicates.is_empty()
                && meta.capture_exclusions.is_empty()
                && meta.lexical_escapes.is_empty()
                && meta.omitted_keys.is_empty()
                && meta.empty_rescue.is_none()
                && meta.default_fallback.is_none() =>
        {
            Some(
                Predicate::from(Guard::Absent {
                    path: helm_schema_core::append_value_path(path, key),
                })
                .negated(),
            )
        }
        AbstractValue::Top
        | AbstractValue::Unknown
        | AbstractValue::RangeKey(_)
        | AbstractValue::KeysList(_)
        | AbstractValue::OutputPath(_, _)
        | AbstractValue::RootContext
        | AbstractValue::StringSet(_)
        | AbstractValue::DerivedBoolean(_)
        | AbstractValue::List(_)
        | AbstractValue::SplitList { .. }
        | AbstractValue::SplitSegment { .. }
        | AbstractValue::Widened(_) => None,
    }
}

/// The deepest path of a set forming one ancestor CHAIN (every path an
/// ancestor of the next); `None` for unrelated paths.
fn ancestor_chain_leaf(paths: &std::collections::BTreeSet<String>) -> Option<&str> {
    let mut ordered: Vec<&String> = paths.iter().collect();
    ordered.sort_by_key(|path| helm_schema_core::split_value_path(path).len());
    for pair in ordered.windows(2) {
        let [ancestor, descendant] = pair else {
            continue;
        };
        if !helm_schema_core::values_path_is_descendant(descendant, ancestor) {
            return None;
        }
    }
    ordered.last().map(|path| path.as_str())
}

fn bool_predicate(value: bool) -> Predicate {
    if value {
        Predicate::True
    } else {
        Predicate::False
    }
}

/// The mapping whose member count `expr` computes: `len (keys M)` or the
/// pipeline form `keys M | len`.
fn keys_len_subject(expr: &TemplateExpr) -> Option<&TemplateExpr> {
    fn keys_map(candidate: &TemplateExpr) -> Option<&TemplateExpr> {
        match candidate.deparen() {
            TemplateExpr::Call { function, args } if function == "keys" => match args.as_slice() {
                [map_expr] => Some(map_expr),
                _ => None,
            },
            _ => None,
        }
    }
    match expr.deparen() {
        TemplateExpr::Call { function, args } if function == "len" => match args.as_slice() {
            [inner] => keys_map(inner),
            _ => None,
        },
        TemplateExpr::Pipeline(stages) => match stages.as_slice() {
            [first, last] => {
                let piped_len = matches!(
                    last.deparen(),
                    TemplateExpr::Call { function, args } if function == "len" && args.is_empty()
                );
                piped_len.then(|| keys_map(first)).flatten()
            }
            _ => None,
        },
        _ => None,
    }
}

/// The subject of a total stringification — `toString X` or the two-stage
/// pipeline `X | toString` (vault's `.Values.server.ha.enabled | toString`
/// redundancy-zone gates spell it this way).
fn tostring_wrapped_subject(expr: &TemplateExpr) -> Option<&TemplateExpr> {
    match expr.deparen() {
        TemplateExpr::Call { function, args } if function == "toString" => {
            let [subject] = args.as_slice() else {
                return None;
            };
            Some(subject)
        }
        TemplateExpr::Pipeline(stages) => {
            let [subject, tail] = stages.as_slice() else {
                return None;
            };
            let TemplateExpr::Call { function, args } = tail.deparen() else {
                return None;
            };
            (function == "toString" && args.is_empty()).then_some(subject)
        }
        _ => None,
    }
}

fn is_tostring_selector(expr: &TemplateExpr) -> bool {
    tostring_wrapped_subject(expr).is_some_and(|subject| {
        matches!(
            subject.deparen(),
            TemplateExpr::Field(_) | TemplateExpr::Selector { .. }
        )
    })
}

/// The `(fallback, subject)` of a literal-fallback `default` call —
/// `default D X` or the two-stage pipeline `X | default D`.
fn default_call_operand(expr: &TemplateExpr) -> Option<(GuardValue, &TemplateExpr)> {
    match expr.deparen() {
        TemplateExpr::Call { function, args } if function == "default" => {
            let [fallback, subject] = args.as_slice() else {
                return None;
            };
            Some((guard_value_literal(fallback)?, subject))
        }
        TemplateExpr::Pipeline(stages) => {
            let [subject, tail] = stages.as_slice() else {
                return None;
            };
            let TemplateExpr::Call { function, args } = tail.deparen() else {
                return None;
            };
            let [fallback] = args.as_slice() else {
                return None;
            };
            if function != "default" {
                return None;
            }
            Some((guard_value_literal(fallback)?, subject))
        }
        _ => None,
    }
}

/// Helm truthiness of a literal guard value (sprig `empty` complement):
/// nil, `""`, `0`, `0.0`, and `false` are falsy.
pub(crate) fn guard_value_is_truthy(value: &GuardValue) -> bool {
    match value {
        GuardValue::String(text) => !text.is_empty(),
        GuardValue::Bool(value) => *value,
        GuardValue::Int(value) => *value != 0,
        GuardValue::Float(text) => text.parse::<f64>().is_ok_and(|value| value != 0.0),
        GuardValue::Null => false,
    }
}

/// A `.Capabilities.KubeVersion.Version` / `.GitVersion` selector (also the
/// `$.`-rooted spelling).
fn capabilities_kube_version_selector(expr: &TemplateExpr) -> bool {
    let path = match expr {
        TemplateExpr::Field(path) => path.as_slice(),
        TemplateExpr::Selector { operand, path } if matches!(operand.as_ref(), TemplateExpr::Variable(variable) if variable.is_empty()) => {
            path.as_slice()
        }
        _ => return false,
    };
    matches!(
        path,
        [first, second, third]
            if first == "Capabilities"
                && second == "KubeVersion"
                && (third == "Version" || third == "GitVersion")
    )
}

fn guard_value_literal(expr: &TemplateExpr) -> Option<GuardValue> {
    match expr.deparen() {
        TemplateExpr::Literal(Literal::String(value) | Literal::RawString(value)) => {
            Some(GuardValue::string(value))
        }
        TemplateExpr::Literal(Literal::Bool(value)) => Some(GuardValue::Bool(*value)),
        TemplateExpr::Literal(Literal::Int(value)) => Some(GuardValue::Int(*value)),
        TemplateExpr::Literal(Literal::Float(value)) => GuardValue::float(*value),
        TemplateExpr::Literal(Literal::Nil) => Some(GuardValue::Null),
        _ => None,
    }
}

#[cfg(test)]
#[path = "../tests/value_path_context/condition_predicate.rs"]
mod tests;