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
use std::collections::{BTreeMap, BTreeSet};

use crate::helper_meta::HelperOutputMeta;

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[expect(
    clippy::large_enum_variant,
    reason = "boxing common abstract values would add allocation and pointer chasing in the evaluator hot path"
)]
pub(crate) enum AbstractValue {
    Top,
    Unknown,
    ValuesPath(String),
    /// Input identity whose runtime value came back through JSON decoding.
    JsonDecodedPath(String),
    /// Key produced by directly ranging a values-backed collection.
    RangeKey(String),
    /// The list of keys of the values-backed collection at path (`keys m`).
    /// Ranging it binds the item to [`Self::RangeKey`], so plucking that
    /// key back out of the same collection is a member projection.
    KeysList(String),
    OutputPath(String, HelperOutputMeta),
    RootContext,
    StringSet(BTreeSet<String>),
    /// Boolean result computed from other values. Its influences are not
    /// the Boolean's raw runtime identity.
    DerivedBoolean(BTreeSet<String>),
    Dict(BTreeMap<String, AbstractValue>),
    List(Vec<AbstractValue>),
    Overlay {
        entries: BTreeMap<String, AbstractValue>,
        fallback: Box<AbstractValue>,
    },
    Choice(BTreeSet<AbstractValue>),
    /// First-Helm-truthy selection among ordered candidates (a `default`
    /// chain: `A | default B | default C`). The runtime value is the first
    /// truthy candidate, or the LAST candidate verbatim when none is truthy
    /// (`default` never tests its fallback). Influence-wise it behaves like
    /// [`Self::Choice`] over the candidates; the ordering survives so a
    /// range over the selected value can claim per-candidate iterable
    /// domains (`truthy(A) ⇒ iterable(A)`, `¬truthy(A) ∧ truthy(B) ⇒
    /// iterable(B)`) instead of the self-truthy approximation that would
    /// falsely reject a truthy scalar beside a selected collection.
    FirstTruthy(Vec<AbstractValue>),
    /// Ordered Sprig `merge` of values-backed layers, highest precedence
    /// first: an earlier layer's key shadows the same key of every later
    /// layer. Influence-wise it behaves like [`Self::Choice`] over the
    /// layers; the ordering survives so sink projection can scope a later
    /// layer's member contracts to keys the earlier layers do not supply.
    MergedLayers(Vec<AbstractValue>),
    /// List produced by splitting derived text. The source paths are
    /// influences rather than list identities; literal indexing uses the
    /// separator to recover a bounded source-cardinality precondition.
    SplitList {
        source_paths: BTreeSet<String>,
        separator: String,
        total_text_preimage: bool,
    },
    /// One separator-delimited segment of split derived text (`regexSplit
    /// ":" . -1 | last`). Like [`Self::SplitList`], the source paths are
    /// influences, but a typed sink can constrain the named segment.
    SplitSegment {
        source_paths: BTreeSet<String>,
        separator: String,
        /// The LAST segment when true, the first otherwise.
        last: bool,
        total_text_preimage: bool,
    },
    /// Result of a call without a transfer function: the value itself is
    /// unknown (structural operations treat it like `Unknown`), but the
    /// `.Values` paths that flowed into the call are kept so output
    /// projection can still attribute the rendered text to its sources.
    /// Declared last so projected rows sort after structured alternatives.
    Widened(BTreeSet<String>),
}

fn flattened_merge_layers(layers: &[AbstractValue]) -> Vec<&AbstractValue> {
    let mut flat = Vec::new();
    for layer in layers {
        match layer {
            AbstractValue::MergedLayers(inner) => flat.extend(flattened_merge_layers(inner)),
            other => flat.push(other),
        }
    }
    flat
}

impl AbstractValue {
    pub(crate) fn values_root() -> Self {
        Self::ValuesPath(String::new())
    }

    pub(crate) fn paths(&self) -> BTreeSet<String> {
        let mut paths = BTreeSet::new();
        self.collect_paths(&mut paths, true, false);
        paths
    }

    pub(crate) fn range_key_paths(&self) -> BTreeSet<String> {
        let mut paths = BTreeSet::new();
        self.collect_range_key_paths(&mut paths);
        paths
    }

    fn collect_range_key_paths(&self, out: &mut BTreeSet<String>) {
        match self {
            Self::RangeKey(path) => {
                out.insert(path.clone());
            }
            Self::Dict(map) => {
                for value in map.values() {
                    value.collect_range_key_paths(out);
                }
            }
            Self::List(items) => {
                for value in items {
                    value.collect_range_key_paths(out);
                }
            }
            Self::Overlay { entries, fallback } => entries
                .values()
                .chain(std::iter::once(fallback.as_ref()))
                .for_each(|value| value.collect_range_key_paths(out)),
            Self::Choice(choices) => {
                for value in choices {
                    value.collect_range_key_paths(out);
                }
            }
            Self::FirstTruthy(candidates) => {
                for value in candidates {
                    value.collect_range_key_paths(out);
                }
            }
            Self::MergedLayers(layers) => {
                for value in layers {
                    value.collect_range_key_paths(out);
                }
            }
            Self::Top
            | Self::Unknown
            | Self::ValuesPath(_)
            | Self::JsonDecodedPath(_)
            | Self::KeysList(_)
            | Self::OutputPath(_, _)
            | Self::RootContext
            | Self::StringSet(_)
            | Self::DerivedBoolean(_)
            | Self::SplitList { .. }
            | Self::SplitSegment { .. }
            | Self::Widened(_) => {}
        }
    }

    fn collect_paths(
        &self,
        out: &mut BTreeSet<String>,
        descend_structures: bool,
        suppress_values_root: bool,
    ) {
        match self {
            Self::ValuesPath(path) | Self::JsonDecodedPath(path) => {
                if !suppress_values_root || !path.is_empty() {
                    out.insert(path.clone());
                }
            }
            Self::OutputPath(path, _) => {
                out.insert(path.clone());
            }
            Self::Dict(map) if descend_structures => {
                for value in map.values() {
                    value.collect_paths(out, descend_structures, suppress_values_root);
                }
            }
            Self::List(items) if descend_structures => {
                for value in items {
                    value.collect_paths(out, descend_structures, suppress_values_root);
                }
            }
            Self::Overlay { entries, fallback } => entries
                .values()
                .chain(std::iter::once(fallback.as_ref()))
                .for_each(|value| {
                    value.collect_paths(out, descend_structures, suppress_values_root);
                }),
            Self::Choice(choices) => {
                for value in choices {
                    value.collect_paths(out, descend_structures, suppress_values_root);
                }
            }
            Self::FirstTruthy(candidates) => {
                for value in candidates {
                    value.collect_paths(out, descend_structures, suppress_values_root);
                }
            }
            Self::MergedLayers(layers) => {
                for value in layers {
                    value.collect_paths(out, descend_structures, suppress_values_root);
                }
            }
            // The derived keys list influences output without carrying the
            // collection's member values.
            Self::KeysList(path) => {
                if !suppress_values_root {
                    out.insert(path.clone());
                }
            }
            // Influence paths surface in full path collection (output
            // attribution), but a widened value is not a fragment source:
            // fragment projections must treat it like `Unknown`.
            Self::Widened(paths)
            | Self::DerivedBoolean(paths)
            | Self::SplitList {
                source_paths: paths,
                ..
            }
            | Self::SplitSegment {
                source_paths: paths,
                ..
            } => {
                if !suppress_values_root {
                    out.extend(paths.iter().cloned());
                }
            }
            Self::Top
            | Self::Unknown
            | Self::RangeKey(_)
            | Self::RootContext
            | Self::StringSet(_)
            | Self::Dict(_)
            | Self::List(_) => {}
        }
    }

    pub(crate) fn strings(&self) -> BTreeSet<String> {
        match self {
            Self::StringSet(strings) => strings.clone(),
            Self::Choice(choices) => choices.iter().flat_map(Self::strings).collect(),
            Self::FirstTruthy(candidates) => candidates.iter().flat_map(Self::strings).collect(),
            _ => BTreeSet::new(),
        }
    }

    pub(crate) fn output_meta(&self) -> BTreeMap<String, HelperOutputMeta> {
        let mut out = BTreeMap::new();
        self.collect_output_meta(&mut out);
        out
    }

    pub(crate) fn with_output_meta(
        self,
        meta_by_path: &BTreeMap<String, HelperOutputMeta>,
    ) -> Self {
        match self {
            Self::ValuesPath(path) => match meta_by_path.get(&path) {
                Some(meta) => Self::OutputPath(path, meta.clone()),
                None => Self::ValuesPath(path),
            },
            Self::JsonDecodedPath(path) => match meta_by_path.get(&path) {
                Some(meta) => {
                    let mut meta = meta.clone();
                    meta.json_decoded = true;
                    Self::OutputPath(path, meta)
                }
                None => Self::JsonDecodedPath(path),
            },
            Self::OutputPath(path, mut meta) => {
                if let Some(extra) = meta_by_path.get(&path) {
                    meta.merge(extra);
                }
                Self::OutputPath(path, meta)
            }
            Self::Dict(entries) => Self::Dict(
                entries
                    .into_iter()
                    .map(|(key, value)| (key, value.with_output_meta(meta_by_path)))
                    .collect(),
            ),
            Self::List(items) => Self::List(
                items
                    .into_iter()
                    .map(|value| value.with_output_meta(meta_by_path))
                    .collect(),
            ),
            Self::Overlay { entries, fallback } => Self::Overlay {
                entries: entries
                    .into_iter()
                    .map(|(key, value)| (key, value.with_output_meta(meta_by_path)))
                    .collect(),
                fallback: Box::new(fallback.with_output_meta(meta_by_path)),
            },
            Self::Choice(choices) => Self::Choice(
                choices
                    .into_iter()
                    .map(|value| value.with_output_meta(meta_by_path))
                    .collect(),
            ),
            Self::FirstTruthy(candidates) => Self::FirstTruthy(
                candidates
                    .into_iter()
                    .map(|value| value.with_output_meta(meta_by_path))
                    .collect(),
            ),
            other => other,
        }
    }

    fn collect_output_meta(&self, out: &mut BTreeMap<String, HelperOutputMeta>) {
        match self {
            Self::OutputPath(path, meta) => out.entry(path.clone()).or_default().merge(meta),
            Self::Dict(entries) => {
                for value in entries.values() {
                    value.collect_output_meta(out);
                }
            }
            Self::List(items) => {
                for value in items {
                    value.collect_output_meta(out);
                }
            }
            Self::Overlay { entries, fallback } => {
                for value in entries.values() {
                    value.collect_output_meta(out);
                }
                fallback.collect_output_meta(out);
            }
            Self::Choice(choices) => {
                for value in choices {
                    value.collect_output_meta(out);
                }
            }
            Self::FirstTruthy(candidates) => {
                for value in candidates {
                    value.collect_output_meta(out);
                }
            }
            Self::MergedLayers(layers) => {
                for value in layers {
                    value.collect_output_meta(out);
                }
                // When every layer IS a path identity, each layer path's
                // binding meta carries its place in the merge: a local
                // bound to the merge renders the MERGED value, so the
                // per-path rows the binding produces must keep the layer
                // scoping (shadowed members stay open, scrubbed layers
                // null-relax) instead of typing each path unconditionally.
                // Nested merges flatten in precedence order — nesting is
                // associative, so an inner merge's layers slot into the
                // outer order where the inner merge stood (airflow's
                // per-set merge over the celery-merged workers base).
                let layers = flattened_merge_layers(layers);
                let identities: Option<Vec<String>> = layers
                    .iter()
                    .map(|layer| layer.merge_layer_identity())
                    .collect();
                if let Some(layer_paths) = identities
                    && layer_paths.len() > 1
                    && layer_paths.iter().all(|path| !path.is_empty())
                {
                    let nil_scrubbed_layers: Vec<bool> = layers
                        .iter()
                        .map(
                            |layer| matches!(layer, Self::OutputPath(_, meta) if meta.nil_scrubbed),
                        )
                        .collect();
                    for (position, layer_path) in layer_paths.iter().enumerate() {
                        let entry = out.entry(layer_path.clone()).or_default();
                        entry.merge_layers = Some(helm_schema_core::MergeLayersUse {
                            layers: layer_paths.clone(),
                            position,
                            nil_scrubbed_layers: nil_scrubbed_layers.clone(),
                            via_binding: true,
                        });
                    }
                }
            }
            Self::Top
            | Self::Unknown
            | Self::ValuesPath(_)
            | Self::JsonDecodedPath(_)
            | Self::RangeKey(_)
            | Self::KeysList(_)
            | Self::RootContext
            | Self::StringSet(_)
            | Self::DerivedBoolean(_)
            | Self::SplitList { .. }
            | Self::SplitSegment { .. }
            | Self::Widened(_) => {}
        }
    }

    pub(crate) fn require_rendered_source_presence(self) -> Self {
        match self {
            Self::ValuesPath(path) | Self::JsonDecodedPath(path) => {
                let mut meta = HelperOutputMeta::default();
                meta.conjoin_branches(&BTreeSet::from([helm_schema_core::Predicate::from(
                    helm_schema_core::Guard::Absent { path: path.clone() },
                )
                .negated()]));
                Self::OutputPath(path, meta)
            }
            Self::OutputPath(path, mut meta) => {
                meta.conjoin_branches(&BTreeSet::from([helm_schema_core::Predicate::from(
                    helm_schema_core::Guard::Absent { path: path.clone() },
                )
                .negated()]));
                Self::OutputPath(path, meta)
            }
            Self::Dict(entries) => Self::Dict(
                entries
                    .into_iter()
                    .map(|(key, value)| (key, value.require_rendered_source_presence()))
                    .collect(),
            ),
            Self::List(items) => Self::List(
                items
                    .into_iter()
                    .map(Self::require_rendered_source_presence)
                    .collect(),
            ),
            Self::Overlay { entries, fallback } => Self::Overlay {
                entries: entries
                    .into_iter()
                    .map(|(key, value)| (key, value.require_rendered_source_presence()))
                    .collect(),
                fallback: Box::new(fallback.require_rendered_source_presence()),
            },
            Self::Choice(choices) => Self::Choice(
                choices
                    .into_iter()
                    .map(Self::require_rendered_source_presence)
                    .collect(),
            ),
            Self::FirstTruthy(candidates) => Self::FirstTruthy(
                candidates
                    .into_iter()
                    .map(Self::require_rendered_source_presence)
                    .collect(),
            ),
            other => other,
        }
    }

    pub(crate) fn fragment_range_item(&self) -> Option<Self> {
        match self {
            Self::ValuesPath(path) => Some(Self::ValuesPath(item_path(path))),
            Self::KeysList(path) => Some(Self::RangeKey(path.clone())),
            Self::JsonDecodedPath(path) => Some(Self::JsonDecodedPath(item_path(path))),
            Self::OutputPath(path, meta) if meta.json_decoded => {
                Some(Self::OutputPath(item_path(path), meta.clone()))
            }
            Self::OutputPath(path, meta) => Some(Self::OutputPath(path.clone(), meta.clone())),
            Self::List(items) => Self::choice(items.clone()),
            Self::SplitList { .. } | Self::SplitSegment { .. } => Some(Self::Unknown),
            Self::Choice(choices) => Self::choice(
                choices
                    .iter()
                    .filter_map(Self::fragment_range_item)
                    .collect(),
            ),
            // The item is a member of the SELECTED candidate; the unordered
            // union over-approximates that soundly.
            Self::FirstTruthy(candidates) => Self::choice(
                candidates
                    .iter()
                    .filter_map(Self::fragment_range_item)
                    .collect(),
            ),
            // Ranging the merged map visits members of every layer, so the
            // item domain is the union regardless of per-key precedence.
            Self::MergedLayers(layers) => Self::choice(
                layers
                    .iter()
                    .filter_map(Self::fragment_range_item)
                    .collect(),
            ),
            // An overlay's range visits its literal entries AND the members
            // of what it overlays, so the item domain is that union — the
            // same rule the merge layers follow. Without it, ranging a
            // `set`-mutated local dict (traefik's `$services :=
            // .Values.service.additionalServices` plus a synthetic
            // "default" entry) loses every member identity and the members'
            // own consumers bind nothing.
            Self::Overlay { entries, fallback } => Self::choice(
                entries
                    .values()
                    .cloned()
                    .chain(fallback.fragment_range_item())
                    .collect(),
            ),
            Self::Top
            | Self::Unknown
            | Self::RangeKey(_)
            | Self::RootContext
            | Self::StringSet(_)
            | Self::DerivedBoolean(_)
            | Self::Dict(_)
            | Self::Widened(_) => None,
        }
    }

    pub(crate) fn definitely_nonempty_iterable(&self) -> bool {
        match self {
            Self::Dict(entries) | Self::Overlay { entries, .. } => !entries.is_empty(),
            Self::List(items) => !items.is_empty(),
            Self::SplitList { .. } => true,
            Self::Choice(choices) => {
                !choices.is_empty() && choices.iter().all(Self::definitely_nonempty_iterable)
            }
            Self::FirstTruthy(candidates) => {
                !candidates.is_empty() && candidates.iter().all(Self::definitely_nonempty_iterable)
            }
            _ => false,
        }
    }

    pub(crate) fn static_truthiness(&self) -> Option<bool> {
        match self {
            Self::StringSet(strings) => {
                let all_empty = strings.iter().all(String::is_empty);
                let all_nonempty = strings.iter().all(|value| !value.is_empty());
                match (all_empty, all_nonempty) {
                    (true, false) => Some(false),
                    (false, true) => Some(true),
                    _ => None,
                }
            }
            Self::Dict(entries) => Some(!entries.is_empty()),
            Self::List(items) => Some(!items.is_empty()),
            Self::Overlay { entries, fallback } => (!entries.is_empty())
                .then_some(true)
                .or_else(|| fallback.static_truthiness()),
            Self::RootContext => Some(true),
            Self::Choice(choices) => {
                let mut truthiness = choices.iter().map(Self::static_truthiness);
                let first = truthiness.next()??;
                truthiness
                    .all(|candidate| candidate == Some(first))
                    .then_some(first)
            }
            // The selected value is one of the candidates, so an agreed
            // truthiness carries over (the same rule as `Choice`).
            Self::FirstTruthy(candidates) => {
                let mut truthiness = candidates.iter().map(Self::static_truthiness);
                let first = truthiness.next()??;
                truthiness
                    .all(|candidate| candidate == Some(first))
                    .then_some(first)
            }
            // The merged map is nonempty exactly when some layer is.
            Self::MergedLayers(layers) => {
                let truthiness: Vec<Option<bool>> =
                    layers.iter().map(Self::static_truthiness).collect();
                if truthiness.contains(&Some(true)) {
                    Some(true)
                } else if truthiness.iter().all(|candidate| *candidate == Some(false)) {
                    Some(false)
                } else {
                    None
                }
            }
            Self::Top
            | Self::Unknown
            | Self::ValuesPath(_)
            | Self::JsonDecodedPath(_)
            | Self::RangeKey(_)
            | Self::KeysList(_)
            | Self::OutputPath(_, _)
            | Self::DerivedBoolean(_)
            | Self::SplitList { .. }
            | Self::SplitSegment { .. }
            | Self::Widened(_) => None,
        }
    }

    pub(crate) fn choice(values: Vec<Self>) -> Option<Self> {
        Self::join_all(values)
    }

    pub(crate) fn path_choices(paths: BTreeSet<String>) -> Option<Self> {
        Self::choice(paths.into_iter().map(Self::ValuesPath).collect())
    }

    pub(crate) fn widened(paths: BTreeSet<String>) -> Option<Self> {
        if paths.is_empty() {
            None
        } else {
            Some(Self::Widened(paths))
        }
    }

    /// A widened value flows to output projection, but it is not a
    /// values-backed fragment: binding it to a local must behave like the
    /// unknown call results did before provenance carrying, i.e. not bind.
    pub(crate) fn without_widened(self) -> Option<Self> {
        match self {
            Self::Widened(_) => None,
            Self::Choice(choices) => Self::choice(
                choices
                    .into_iter()
                    .filter_map(Self::without_widened)
                    .collect(),
            ),
            // Dropping a candidate would misstate the selection order, so a
            // chain that loses one degrades to the unordered choice.
            Self::FirstTruthy(candidates) => {
                let mapped: Vec<Option<Self>> =
                    candidates.into_iter().map(Self::without_widened).collect();
                let intact = mapped.iter().all(Option::is_some);
                let kept: Vec<Self> = mapped.into_iter().flatten().collect();
                if intact {
                    Self::first_truthy(kept)
                } else {
                    Self::choice(kept)
                }
            }
            other => Some(other),
        }
    }

    pub(crate) fn mark_json_decoded(self) -> Self {
        match self {
            Self::ValuesPath(path) => Self::JsonDecodedPath(path),
            Self::OutputPath(path, mut meta) => {
                meta.json_decoded = true;
                Self::OutputPath(path, meta)
            }
            Self::Dict(entries) => Self::Dict(
                entries
                    .into_iter()
                    .map(|(key, value)| (key, value.mark_json_decoded()))
                    .collect(),
            ),
            Self::List(items) => {
                Self::List(items.into_iter().map(Self::mark_json_decoded).collect())
            }
            Self::Overlay { entries, fallback } => Self::Overlay {
                entries: entries
                    .into_iter()
                    .map(|(key, value)| (key, value.mark_json_decoded()))
                    .collect(),
                fallback: Box::new(fallback.mark_json_decoded()),
            },
            Self::Choice(choices) => {
                Self::Choice(choices.into_iter().map(Self::mark_json_decoded).collect())
            }
            Self::FirstTruthy(candidates) => Self::FirstTruthy(
                candidates
                    .into_iter()
                    .map(Self::mark_json_decoded)
                    .collect(),
            ),
            Self::MergedLayers(layers) => {
                Self::MergedLayers(layers.into_iter().map(Self::mark_json_decoded).collect())
            }
            Self::Widened(paths) => {
                Self::choice(paths.into_iter().map(Self::JsonDecodedPath).collect())
                    .unwrap_or(Self::Unknown)
            }
            Self::JsonDecodedPath(_)
            | Self::Top
            | Self::Unknown
            | Self::RangeKey(_)
            | Self::KeysList(_)
            | Self::RootContext
            | Self::StringSet(_)
            | Self::DerivedBoolean(_)
            | Self::SplitList { .. }
            | Self::SplitSegment { .. } => self,
        }
    }

    /// Keep only identities that remain unambiguous across a JSON roundtrip.
    /// Direct values paths retain their identity. Container structure
    /// roundtrips member-wise: a member that IS a path identity keeps that
    /// identity in the decoded copy (reading the copy reads the same chart
    /// value; `set` mutations on the copy ride the local's overlay
    /// machinery, never the path), literal structure survives verbatim, and
    /// anything else stays an opaque PRESENT member — dropping it would
    /// fabricate absence for `hasKey`-style probes (the nats `jsonpatch`
    /// helper ranges the `patch` member of a roundtripped call dict).
    /// Strip nil-scrub layers recursively, degrading scrubbed identities
    /// to the opaque form the analysis produced before the scrub decode
    /// existed: consumers then treat the value exactly as they did then.
    pub(crate) fn without_nil_scrub_markers(self) -> Self {
        match self {
            Self::OutputPath(_, meta) if meta.nil_scrubbed => Self::Unknown,
            Self::MergedLayers(layers) => Self::MergedLayers(
                layers
                    .into_iter()
                    .map(Self::without_nil_scrub_markers)
                    .collect(),
            ),
            Self::Choice(choices) => Self::Choice(
                choices
                    .into_iter()
                    .map(Self::without_nil_scrub_markers)
                    .collect(),
            ),
            Self::FirstTruthy(candidates) => Self::FirstTruthy(
                candidates
                    .into_iter()
                    .map(Self::without_nil_scrub_markers)
                    .collect(),
            ),
            Self::Dict(entries) => Self::Dict(
                entries
                    .into_iter()
                    .map(|(key, value)| (key, value.without_nil_scrub_markers()))
                    .collect(),
            ),
            other => other,
        }
    }

    pub(crate) fn json_roundtrip_identity(&self) -> Option<Self> {
        fn member(value: &AbstractValue) -> AbstractValue {
            value
                .json_roundtrip_identity()
                .unwrap_or(AbstractValue::Unknown)
        }
        match self {
            Self::ValuesPath(_) | Self::JsonDecodedPath(_) | Self::OutputPath(_, _) => {
                Some(self.clone().mark_json_decoded())
            }
            Self::StringSet(_) | Self::DerivedBoolean(_) => Some(self.clone()),
            Self::Dict(entries) => Some(Self::Dict(
                entries
                    .iter()
                    .map(|(key, value)| (key.clone(), member(value)))
                    .collect(),
            )),
            Self::List(items) => Some(Self::List(items.iter().map(member).collect())),
            Self::Overlay { entries, fallback } => Some(Self::Overlay {
                entries: entries
                    .iter()
                    .map(|(key, value)| (key.clone(), member(value)))
                    .collect(),
                fallback: Box::new(member(fallback)),
            }),
            Self::Choice(choices) => {
                Self::choice(choices.iter().map(member).collect()).map(Self::mark_json_decoded)
            }
            Self::FirstTruthy(candidates) => {
                Self::choice(candidates.iter().map(member).collect()).map(Self::mark_json_decoded)
            }
            _ => self.values_root_structure().map(Self::mark_json_decoded),
        }
    }

    pub(crate) fn values_root_structure(&self) -> Option<Self> {
        match self {
            Self::ValuesPath(path) | Self::JsonDecodedPath(path) if path.is_empty() => {
                Some(self.clone())
            }
            Self::OutputPath(path, _) if path.is_empty() => Some(self.clone()),
            Self::Dict(entries) => {
                let entries = entries
                    .iter()
                    .filter_map(|(key, value)| {
                        value
                            .values_root_structure()
                            .map(|value| (key.clone(), value))
                    })
                    .collect::<BTreeMap<_, _>>();
                (!entries.is_empty()).then_some(Self::Dict(entries))
            }
            Self::Overlay { entries, fallback } => {
                if let Some(fallback) = fallback.values_root_structure() {
                    return Some(fallback);
                }
                let entries = entries
                    .iter()
                    .filter_map(|(key, value)| {
                        value
                            .values_root_structure()
                            .map(|value| (key.clone(), value))
                    })
                    .collect::<BTreeMap<_, _>>();
                (!entries.is_empty()).then_some(Self::Dict(entries))
            }
            Self::Choice(choices) => Self::choice(
                choices
                    .iter()
                    .filter_map(Self::values_root_structure)
                    .collect(),
            ),
            Self::FirstTruthy(candidates) => Self::choice(
                candidates
                    .iter()
                    .filter_map(Self::values_root_structure)
                    .collect(),
            ),
            Self::MergedLayers(layers) => Self::choice(
                layers
                    .iter()
                    .filter_map(Self::values_root_structure)
                    .collect(),
            ),
            Self::Top
            | Self::Unknown
            | Self::ValuesPath(_)
            | Self::JsonDecodedPath(_)
            | Self::RangeKey(_)
            | Self::KeysList(_)
            | Self::OutputPath(_, _)
            | Self::RootContext
            | Self::StringSet(_)
            | Self::DerivedBoolean(_)
            | Self::List(_)
            | Self::SplitList { .. }
            | Self::SplitSegment { .. }
            | Self::Widened(_) => None,
        }
    }

    pub(crate) fn unique_json_decoded_path(&self) -> Option<String> {
        let path = match self {
            Self::JsonDecodedPath(path) => path,
            Self::OutputPath(path, meta) if meta.json_decoded => path,
            Self::Choice(choices)
                if !choices.is_empty()
                    && choices
                        .iter()
                        .all(|choice| choice.unique_json_decoded_path().is_some()) =>
            {
                let mut paths = choices.iter().filter_map(Self::unique_json_decoded_path);
                let first = paths.next()?;
                return paths.all(|path| path == first).then_some(first);
            }
            Self::FirstTruthy(candidates)
                if !candidates.is_empty()
                    && candidates
                        .iter()
                        .all(|candidate| candidate.unique_json_decoded_path().is_some()) =>
            {
                let mut paths = candidates.iter().filter_map(Self::unique_json_decoded_path);
                let first = paths.next()?;
                return paths.all(|path| path == first).then_some(first);
            }
            _ => return None,
        };
        Some(path.clone())
    }

    pub(crate) fn is_definitely_json_serialized(&self) -> bool {
        match self {
            Self::OutputPath(_, meta) => meta.json_serialized,
            Self::Dict(entries) => {
                !entries.is_empty() && entries.values().all(Self::is_definitely_json_serialized)
            }
            Self::List(items) => {
                !items.is_empty() && items.iter().all(Self::is_definitely_json_serialized)
            }
            Self::Overlay { entries, fallback } => {
                !entries.is_empty()
                    && entries.values().all(Self::is_definitely_json_serialized)
                    && fallback.is_definitely_json_serialized()
            }
            Self::Choice(choices) => {
                !choices.is_empty() && choices.iter().all(Self::is_definitely_json_serialized)
            }
            Self::FirstTruthy(candidates) => {
                !candidates.is_empty() && candidates.iter().all(Self::is_definitely_json_serialized)
            }
            Self::MergedLayers(layers) => {
                !layers.is_empty() && layers.iter().all(Self::is_definitely_json_serialized)
            }
            Self::Top
            | Self::Unknown
            | Self::ValuesPath(_)
            | Self::JsonDecodedPath(_)
            | Self::RangeKey(_)
            | Self::KeysList(_)
            | Self::RootContext
            | Self::StringSet(_)
            | Self::DerivedBoolean(_)
            | Self::SplitList { .. }
            | Self::SplitSegment { .. }
            | Self::Widened(_) => false,
        }
    }

    pub(crate) fn join_all(values: Vec<Self>) -> Option<Self> {
        let mut flat = BTreeSet::new();
        let mut pending = values;
        while let Some(value) = pending.pop() {
            match value {
                Self::Choice(inner) => pending.extend(inner),
                Self::Unknown => {
                    flat.insert(Self::Top);
                }
                other => {
                    flat.insert(other);
                }
            }
        }
        // An unknown alternative widens the join but must not erase the
        // structured alternatives: path attribution has to survive joins
        // such as `default $unknown .Values.x`. A single Top member records
        // the width.
        match flat.len() {
            0 => None,
            1 => flat.into_iter().next(),
            _ => Some(Self::Choice(flat)),
        }
    }

    /// Normalizing [`Self::MergedLayers`] constructor: no layers is
    /// nothing, a single layer is that layer itself.
    pub(crate) fn merged_layers(layers: Vec<Self>) -> Option<Self> {
        match layers.len() {
            0 => None,
            1 => layers.into_iter().next(),
            _ => Some(Self::MergedLayers(layers)),
        }
    }

    /// Normalizing [`Self::FirstTruthy`] constructor: nested chains flatten
    /// (`a | default b | default c` selects exactly like the flat chain),
    /// and a chain whose candidates are all equal IS that value.
    pub(crate) fn first_truthy(candidates: Vec<Self>) -> Option<Self> {
        let mut flat = Vec::new();
        for candidate in candidates {
            match candidate {
                Self::FirstTruthy(inner) => flat.extend(inner),
                other => flat.push(other),
            }
        }
        flat.dedup();
        match flat.len() {
            0 => None,
            1 => flat.into_iter().next(),
            _ => Some(Self::FirstTruthy(flat)),
        }
    }

    /// The ordered candidate paths of a selection chain whose candidates
    /// are RAW path identities (an `OutputPath` may be a transform of its
    /// path, whose truthiness the selection actually tested — never the
    /// path's own). A non-identity candidate has no nameable truthiness
    /// condition, so the per-candidate decode abstains past it; a literal
    /// TAIL candidate is tolerated because no later candidate needs its
    /// negation.
    pub(crate) fn selection_chain_identity_paths(&self) -> Option<Vec<String>> {
        let Self::FirstTruthy(candidates) = self else {
            return None;
        };
        let mut paths = Vec::new();
        for candidate in candidates {
            match candidate {
                Self::ValuesPath(path) | Self::JsonDecodedPath(path) => paths.push(path.clone()),
                _ => break,
            }
        }
        (!paths.is_empty()).then_some(paths)
    }

    #[expect(
        clippy::too_many_lines,
        reason = "keeping this semantic operation together makes its state transitions easier to audit"
    )]
    pub(crate) fn apply_to_path(&self, rest: &[String]) -> Option<Self> {
        if rest.is_empty() {
            return Some(self.clone());
        }

        match self {
            Self::ValuesPath(prefix) => {
                let mut segments = helm_schema_core::split_value_path(prefix);
                segments.extend(rest.iter().cloned());
                Some(Self::ValuesPath(helm_schema_core::join_value_path(
                    segments,
                )))
            }
            Self::JsonDecodedPath(prefix) => {
                let mut segments = helm_schema_core::split_value_path(prefix);
                segments.extend(rest.iter().cloned());
                Some(Self::JsonDecodedPath(helm_schema_core::join_value_path(
                    segments,
                )))
            }
            Self::OutputPath(prefix, meta) if meta.json_decoded => {
                let mut segments = helm_schema_core::split_value_path(prefix);
                segments.extend(rest.iter().cloned());
                Some(Self::OutputPath(
                    helm_schema_core::join_value_path(segments),
                    meta.clone(),
                ))
            }
            Self::OutputPath(prefix, meta) => Some(Self::OutputPath(prefix.clone(), meta.clone())),
            Self::RootContext => {
                if let Some((segment, remaining)) = rest.split_first()
                    && segment == "Values"
                {
                    let tail = resolve_root_values_methods(remaining)?;
                    if tail.is_empty() {
                        Some(Self::values_root())
                    } else {
                        Some(Self::ValuesPath(helm_schema_core::join_value_path(tail)))
                    }
                } else {
                    None
                }
            }
            Self::Top => Some(Self::Top),
            // Selecting into an unknown call result severs the influence:
            // the selected member is not derived from the recorded paths in
            // any way the projection could still attribute.
            Self::Unknown
            | Self::Widened(_)
            | Self::DerivedBoolean(_)
            | Self::SplitList { .. }
            | Self::SplitSegment { .. }
            | Self::RangeKey(_)
            | Self::KeysList(_)
            | Self::StringSet(_) => None,
            Self::Choice(choices) => {
                let mut out = Vec::new();
                for value in choices {
                    if let Some(bound) = value.apply_to_path(rest) {
                        out.push(bound);
                    }
                }
                Self::choice(out)
            }
            // The member of the SELECTED candidate: selection tests the
            // candidates' own truthiness, not the members', so the ordering
            // does not transfer and the projection degrades to the choice.
            Self::FirstTruthy(candidates) => {
                let mut out = Vec::new();
                for value in candidates {
                    if let Some(bound) = value.apply_to_path(rest) {
                        out.push(bound);
                    }
                }
                Self::choice(out)
            }
            // Member selection distributes over the layers WITH their
            // precedence: mergo recurses into nested maps with the same
            // override order, so `merged.key` is itself a layered merge of
            // the per-layer members. Collapsing to an unordered choice here
            // would erase the shadowing that makes a fully-overridden base
            // member unreachable (kyverno's `featuresOverride.logging`).
            // A layer whose member cannot be resolved drops only when the
            // layer's shape PROVES the member absent; an opaque layer stays
            // as an unknown member that may still shadow everything below
            // it (airflow's nil-filtered celery overwrite layer).
            Self::MergedLayers(layers) => {
                let mut out = Vec::new();
                for value in layers {
                    match value.apply_to_path(rest) {
                        Some(bound) => out.push(bound),
                        None if value.member_projection_is_exhaustive() => {}
                        None => out.push(Self::Unknown),
                    }
                }
                match out.len() {
                    0 => None,
                    1 => out.pop(),
                    _ => Some(Self::MergedLayers(out)),
                }
            }
            Self::Dict(map) => {
                let (head, tail) = rest.split_first()?;
                let value = map.get(head)?;
                value.apply_to_path(tail)
            }
            Self::List(items) => {
                let (head, tail) = rest.split_first()?;
                let index = head.parse::<usize>().ok()?;
                let value = items.get(index)?;
                value.apply_to_path(tail)
            }
            Self::Overlay { entries, fallback } => {
                let (head, tail) = rest.split_first()?;
                if let Some(value) = entries.get(head) {
                    value.apply_to_path(tail)
                } else {
                    fallback.apply_to_path(rest)
                }
            }
        }
    }

    /// Whether a failed [`Self::apply_to_path`] on this value proves the
    /// member absent.
    ///
    /// Structured values enumerate their members (checked recursively,
    /// since a projection can fail at any depth) and scalars have none, so
    /// a miss is a genuine absence; opaque values (unknown call results,
    /// derived text) may hold the member without the projection seeing it.
    fn member_projection_is_exhaustive(&self) -> bool {
        match self {
            // Path-backed values and `Top` never fail a projection, and
            // scalar shapes genuinely have no members. `RootContext` fails
            // only on non-`Values` heads, which never name a user value.
            Self::ValuesPath(_)
            | Self::JsonDecodedPath(_)
            | Self::OutputPath(_, _)
            | Self::Top
            | Self::RootContext
            | Self::StringSet(_)
            | Self::DerivedBoolean(_) => true,
            Self::Dict(entries) => entries.values().all(Self::member_projection_is_exhaustive),
            Self::List(items) => items.iter().all(Self::member_projection_is_exhaustive),
            Self::Overlay { entries, fallback } => {
                entries.values().all(Self::member_projection_is_exhaustive)
                    && fallback.member_projection_is_exhaustive()
            }
            Self::Choice(choices) => choices.iter().all(Self::member_projection_is_exhaustive),
            Self::FirstTruthy(candidates) => {
                candidates.iter().all(Self::member_projection_is_exhaustive)
            }
            Self::MergedLayers(layers) => layers.iter().all(Self::member_projection_is_exhaustive),
            Self::Unknown
            | Self::RangeKey(_)
            | Self::KeysList(_)
            | Self::SplitList { .. }
            | Self::SplitSegment { .. }
            | Self::Widened(_) => false,
        }
    }

    /// Merges `entries` into `map`, joining values that land on an existing
    /// key. Both merge folds share this per-key rule.
    fn merge_entries(map: &mut BTreeMap<String, Self>, entries: BTreeMap<String, Self>) {
        for (key, value) in entries {
            let merged = match map.remove(&key) {
                Some(existing) => Self::choice(vec![existing, value]),
                None => Some(value),
            };
            if let Some(merged) = merged {
                map.insert(key, merged);
            }
        }
    }

    pub(crate) fn merge_all(values: Vec<Self>) -> Option<Self> {
        let mut map = BTreeMap::new();
        let mut non_dict_values = Vec::new();
        let mut pending = values;

        while let Some(value) = pending.pop() {
            match value {
                Self::Choice(choices) => pending.extend(choices),
                Self::FirstTruthy(candidates) => pending.extend(candidates),
                Self::Dict(entries) => Self::merge_entries(&mut map, entries),
                // Top/Unknown deliberately survive as fallback members here,
                // unlike merge_context_values, which keeps only values-backed
                // members.
                other => non_dict_values.push(other),
            }
        }

        let fallback = Self::choice(non_dict_values);
        match (map.is_empty(), fallback) {
            (true, None) => None,
            (false, None) => Some(Self::Dict(map)),
            (true, Some(fallback)) => Some(fallback),
            (false, Some(fallback)) => Some(Self::Overlay {
                entries: map,
                fallback: Box::new(fallback),
            }),
        }
    }

    pub(crate) fn unique_path(&self) -> Option<String> {
        let mut paths = self.paths().into_iter();
        let first = paths.next()?;
        if paths.next().is_none() {
            Some(first)
        } else {
            None
        }
    }

    /// The values path a merge layer's runtime value IS.
    ///
    /// Accepts a direct path identity, possibly alternated with pathless
    /// literal arms (velero's `.Values.podSecurityContext | default dict`
    /// off-state).
    ///
    /// A constructed container REFERENCING a path returns `None` — its keys
    /// are template-supplied (external-dns's `merge $defaultSelector
    /// .podAffinityTerm` selector built from `nameOverride`), so keying the
    /// merge shadow on the referenced path would scope sibling-layer members
    /// by the wrong value.
    pub(crate) fn merge_layer_identity(&self) -> Option<String> {
        fn arms_are_identity_or_literal(value: &AbstractValue) -> bool {
            match value {
                AbstractValue::ValuesPath(_)
                | AbstractValue::JsonDecodedPath(_)
                | AbstractValue::OutputPath(_, _) => true,
                // A nested merge of identities keeps the lineage: airflow's
                // per-set worker context resolves `.Values.workers.x` to
                // `MergedLayers([overwrite, workers.x])`, which still IS the
                // `workers.x` value wherever the overwrite abstains.
                AbstractValue::Choice(choices) => choices.iter().all(arms_are_identity_or_literal),
                AbstractValue::FirstTruthy(candidates) => {
                    candidates.iter().all(arms_are_identity_or_literal)
                }
                AbstractValue::MergedLayers(layers) => {
                    layers.iter().all(arms_are_identity_or_literal)
                }
                other => other.paths().is_empty(),
            }
        }
        arms_are_identity_or_literal(self).then(|| self.unique_path())?
    }

    pub(crate) fn with_overlay_entries(self, new_entries: BTreeMap<String, AbstractValue>) -> Self {
        if new_entries.is_empty() {
            return self;
        }
        match self {
            Self::Overlay {
                mut entries,
                fallback,
            } => {
                entries.extend(new_entries);
                Self::Overlay { entries, fallback }
            }
            other => Self::Overlay {
                entries: new_entries,
                fallback: Box::new(other),
            },
        }
    }

    pub(crate) fn omit_keys(self, keys: &BTreeSet<String>) -> Self {
        if keys.is_empty() {
            return self;
        }

        match self {
            Self::Dict(entries) => Self::Dict(
                entries
                    .into_iter()
                    .filter(|(key, _value)| !keys.contains(key))
                    .collect(),
            ),
            Self::Overlay { entries, fallback } => Self::Overlay {
                entries: entries
                    .into_iter()
                    .filter(|(key, _value)| !keys.contains(key))
                    .collect(),
                fallback: Box::new(fallback.omit_keys(keys)),
            },
            Self::Choice(choices) => Self::Choice(
                choices
                    .into_iter()
                    .map(|choice| choice.omit_keys(keys))
                    .collect(),
            ),
            Self::FirstTruthy(candidates) => Self::FirstTruthy(
                candidates
                    .into_iter()
                    .map(|candidate| candidate.omit_keys(keys))
                    .collect(),
            ),
            other => other,
        }
    }

    #[expect(
        clippy::too_many_lines,
        reason = "keeping this semantic operation together makes its state transitions easier to audit"
    )]
    pub(crate) fn remove_fragment_paths(self, remove: &BTreeSet<String>) -> Option<Self> {
        if remove.is_empty() {
            return Some(self);
        }

        match self {
            Self::ValuesPath(path) if remove.contains(&path) => None,
            Self::JsonDecodedPath(path) if remove.contains(&path) => None,
            Self::OutputPath(path, _) if remove.contains(&path) => None,
            Self::ValuesPath(_)
            | Self::JsonDecodedPath(_)
            | Self::RangeKey(_)
            | Self::KeysList(_)
            | Self::OutputPath(_, _)
            | Self::RootContext
            | Self::Unknown
            | Self::Top
            | Self::StringSet(_) => Some(self),
            Self::DerivedBoolean(paths) => Some(Self::DerivedBoolean(
                paths.difference(remove).cloned().collect(),
            )),
            Self::Widened(paths) => Self::widened(paths.difference(remove).cloned().collect()),
            Self::SplitList {
                source_paths,
                separator,
                total_text_preimage,
            } => {
                let source_paths: BTreeSet<String> =
                    source_paths.difference(remove).cloned().collect();
                (!source_paths.is_empty()).then_some(Self::SplitList {
                    source_paths,
                    separator,
                    total_text_preimage,
                })
            }
            Self::SplitSegment {
                source_paths,
                separator,
                last,
                total_text_preimage,
            } => {
                let source_paths: BTreeSet<String> =
                    source_paths.difference(remove).cloned().collect();
                (!source_paths.is_empty()).then_some(Self::SplitSegment {
                    source_paths,
                    separator,
                    last,
                    total_text_preimage,
                })
            }
            Self::Dict(entries) => {
                let entries = Self::remove_fragment_paths_from_entries(entries, remove);
                if entries.is_empty() {
                    None
                } else {
                    Some(Self::Dict(entries))
                }
            }
            Self::List(items) => {
                let items = items
                    .into_iter()
                    .filter_map(|item| item.remove_fragment_paths(remove))
                    .collect::<Vec<_>>();
                if items.is_empty() {
                    None
                } else {
                    Some(Self::List(items))
                }
            }
            Self::Overlay { entries, fallback } => {
                let entries = Self::remove_fragment_paths_from_entries(entries, remove);
                match (entries.is_empty(), fallback.remove_fragment_paths(remove)) {
                    (true, fallback) => fallback,
                    (false, Some(fallback)) => Some(Self::Overlay {
                        entries,
                        fallback: Box::new(fallback),
                    }),
                    (false, None) => Some(Self::Dict(entries)),
                }
            }
            Self::Choice(choices) => Self::choice(
                choices
                    .into_iter()
                    .filter_map(|choice| choice.remove_fragment_paths(remove))
                    .collect(),
            ),
            // Like `without_widened`: a chain that loses a candidate can no
            // longer state the selection order and degrades to the choice.
            Self::FirstTruthy(candidates) => {
                let mapped: Vec<Option<Self>> = candidates
                    .into_iter()
                    .map(|candidate| candidate.remove_fragment_paths(remove))
                    .collect();
                let intact = mapped.iter().all(Option::is_some);
                let kept: Vec<Self> = mapped.into_iter().flatten().collect();
                if intact {
                    Self::first_truthy(kept)
                } else {
                    Self::choice(kept)
                }
            }
            Self::MergedLayers(layers) => Self::merged_layers(
                layers
                    .into_iter()
                    .filter_map(|layer| layer.remove_fragment_paths(remove))
                    .collect(),
            ),
        }
    }

    fn remove_fragment_paths_from_entries(
        entries: BTreeMap<String, Self>,
        remove: &BTreeSet<String>,
    ) -> BTreeMap<String, Self> {
        entries
            .into_iter()
            .filter_map(|(key, value)| {
                value
                    .remove_fragment_paths(remove)
                    .map(|value| (key, value))
            })
            .collect()
    }

    pub(crate) fn to_context_value(&self) -> Self {
        match self {
            Self::Top => Self::Unknown,
            other => other.clone(),
        }
    }

    pub(crate) fn to_current_dot_context_value(&self) -> Option<Self> {
        match self {
            Self::ValuesPath(path) => Some(Self::ValuesPath(path.clone())),
            Self::JsonDecodedPath(path) => Some(Self::JsonDecodedPath(path.clone())),
            Self::OutputPath(path, meta) => Some(Self::OutputPath(path.clone(), meta.clone())),
            Self::RootContext => Some(Self::RootContext),
            Self::Top
            | Self::Unknown
            | Self::RangeKey(_)
            | Self::KeysList(_)
            | Self::Dict(_)
            | Self::List(_)
            | Self::Overlay { .. }
            | Self::StringSet(_)
            | Self::DerivedBoolean(_)
            | Self::Choice(_)
            | Self::FirstTruthy(_)
            | Self::MergedLayers(_)
            | Self::SplitList { .. }
            | Self::SplitSegment { .. }
            | Self::Widened(_) => None,
        }
    }

    pub(crate) fn fragment_source_paths(&self) -> BTreeSet<String> {
        let mut paths = BTreeSet::new();
        self.collect_paths(&mut paths, false, true);
        paths
    }

    pub(crate) fn fragment_rendered_paths(&self) -> BTreeSet<String> {
        let mut paths = BTreeSet::new();
        self.collect_paths(&mut paths, true, true);
        paths
    }
}

fn item_path(path: &str) -> String {
    helm_schema_core::append_value_path(path, "*")
}

/// Go-template method resolution on the typed root values object.
///
/// Helm's `.Values` is `chartutil.Values`, a named map type whose exported
/// methods shadow same-named map keys during selector resolution. A leading
/// `AsMap` calls the niladic method that returns the receiver map itself
/// (an empty map for nil/empty values), so the remaining segments continue
/// from the root. The other exposed methods (`YAML`, `Table`, `Encode`,
/// `PathValue`) take arguments or produce derived text, so selecting
/// through them never names a user value and resolution abstains instead
/// of fabricating a path segment. Only the ROOT receiver carries the type;
/// nested values are plain maps, so deeper same-named segments stay
/// ordinary keys.
pub(crate) fn resolve_root_values_methods(tail: &[String]) -> Option<&[String]> {
    match tail.split_first() {
        Some((method, rest)) if method == "AsMap" => Some(rest),
        Some((method, _))
            if matches!(method.as_str(), "YAML" | "Table" | "Encode" | "PathValue") =>
        {
            None
        }
        _ => Some(tail),
    }
}

pub(crate) fn path_is_encoded(path: &str, encoded_paths: &BTreeSet<String>) -> bool {
    encoded_paths.iter().any(|encoded_path| {
        path == encoded_path || helm_schema_core::values_path_is_descendant(path, encoded_path)
    })
}

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