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
//! The fragment interpreter: one abstract evaluation of a templated-YAML
//! document over the `helm-schema-syntax` CST, producing a
//! [`Guarded<AbstractFragment>`] plus the pathless value reads that never
//! render (condition reads, assignment right-hand sides, helper-internal
//! guard reads).
//!
//! Control regions become guarded arms: each branch's contributions are
//! evaluated under the branch's decoded [`PathCondition`] and dissolve into
//! the surrounding container, so guard structure lives in the tree instead
//! of ambient per-row stacks. The interpreter still keeps a small predicate
//! stack, but only to stamp root-to-leaf guards onto the pathless reads that
//! have no tree position.
//!
//! Reused machinery (nothing here re-derives what the pipeline already
//! knows how to compute):
//!
//! - condition decoding: [`ValuePathContext`] predicate decoding over
//!   `TemplateHeader`s,
//! - expression evaluation: the `AbstractValue` lattice with bound-helper
//!   resolution (`document_result_from_expr`), where helper calls resolve
//!   through their in-domain fragment summaries (`super::summary`),
//! - range headers: `range_header_from_source` /
//!   `range_has_destructured_variable_definition` on the shared Go-template
//!   parse (body shape comes from the CST),
//! - local state: [`SymbolicLocalState`] with shared branch-join rules.
//!
//! The same interpreter evaluates documents and helper bodies; a helper
//! scope additionally carries the call's root bindings, the resolved dot
//! pair, and the active call chain, and applies the summary lane's
//! flattening rules where the caller consumes summary facts (truthy range
//! markers, dependency-lane demotions, sibling-condition scoping).
//!
//! Known boundaries: document-scope ranges run one symbolic iteration
//! (helper scopes iterate statically known lists exactly); destructured
//! range variables stay unbound at document scope; static file templates
//! evaluate as nested fragments at output holes; ill-nested regions
//! re-adopt escaped siblings by span in both directions, so branch-window
//! content of a container opened before (or closed after) the region
//! inherits the branch guard.

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::rc::Rc;

use helm_schema_ast::{
    ResourceSpan, TemplateExpr, TemplateHeader, parse_expr_text,
    range_has_destructured_variable_definition, range_header_from_source,
};
use helm_schema_syntax as syntax;
use helm_schema_syntax::{
    Node, OpaqueKind, ScalarPart, ScalarParts, Span, TemplatedDocument, parse_go_template,
};

use crate::abstract_value::AbstractValue;
use crate::analysis_db::IrAnalysisDb;
use crate::eval_effect::{CaptureKind, FailCapture};
use crate::fragment_expr_eval::FragmentEvalContext;
use crate::helper_meta::{HelperOutputMeta, merge_provenance_sites};
use crate::node_eval::control_header;
use crate::symbolic_local_state::SymbolicLocalState;
use crate::value_path_context::ValuePathContext;
use crate::{ContractProvenance, Guard, ResourceRef, SourceSpan};
use helm_schema_core::{GuardDnf, Predicate};

use super::domain::{
    AbstractFragment, AbstractString, EntryKey, Guarded, Mapping, MappingEntry, Opaque,
    PathCondition, Sequence, SiteFacts, StringPart, and_conditions,
};

/// The result of evaluating one template source: the abstract rendered
/// document plus the pathless value reads observed along the way.
#[derive(Debug, Default)]
pub struct EvaluatedDocument {
    /// The guarded abstract fragment for the whole source (all YAML
    /// documents merged; per-document projection is a later-stage concern).
    pub root: Guarded<AbstractFragment>,
    /// `.Values` reads that never render: condition reads, assignment
    /// right-hand sides, helper-internal guard reads, and range headers.
    pub reads: Vec<ValueRead>,
    /// Declared input-type hints observed at unconditional rendered holes.
    pub(crate) type_hints: BTreeMap<String, BTreeSet<String>>,
    /// Input-type hints observed only under branch predicates: they hold
    /// where those branches render, never at the unconditional base.
    pub(crate) guarded_type_hints: BTreeMap<String, BTreeSet<String>>,
    /// Input-type hints from literal `default`/`coalesce` fallbacks: they
    /// type only the truthy arm of the path, never its Helm-falsy states.
    pub(crate) fallback_type_hints: BTreeMap<String, BTreeSet<String>>,
    /// Fallback hints observed under branch predicates: fallback-grade
    /// intent that may type conditional overlays, but never a branch whose
    /// renders all totally format.
    pub(crate) guarded_fallback_type_hints: BTreeMap<String, BTreeSet<String>>,
    /// Paths consumed through total stringifications (`quote`, `toString`,
    /// `join`, `printf`) anywhere in the source: the chart tolerates any
    /// input type at them even when no placed row exists.
    pub(crate) shape_erased_paths: BTreeSet<String>,
    /// Paths carrying a real runtime string contract (`trunc`, `b64enc`,
    /// `fromYaml`, a dynamic `printf` format) somewhere in the source.
    pub(crate) string_contract_paths: BTreeSet<String>,
    /// The observed per-path range facts (direct iteration, JSON-decoded
    /// values, key/value destructuring).
    pub(crate) range_modes: crate::range_modes::RangeModes,
    /// Chart value subtrees supplying defaults to the effective values tree.
    pub(crate) values_default_sources: BTreeSet<crate::ValuesDefaultSource>,
    /// Values subtrees merged in place over the values root: root contracts
    /// project back onto the prefixed spellings.
    pub(crate) values_root_overlay_prefixes: BTreeSet<String>,
    /// Helper names through which the values root was replaced.
    pub(crate) values_root_helper_includes: BTreeSet<String>,
    /// Strictly string-consumed paths whose consumers execute BEFORE the
    /// values-root wrapper rewrite: their nodes must not gain the wrapper
    /// alternative (see the interpreter field of the same name).
    pub(crate) pre_rewrite_strict_paths: BTreeSet<String>,
    /// `fail` captures (see [`FailCapture`]): no valid values document may
    /// satisfy one of these conjunctions.
    pub(crate) fail_conditions: Vec<FailCapture>,
}

/// One pathless `.Values` read with the guards active at the read site.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ValueRead {
    /// The dotted `.Values` path that was read.
    pub values_path: String,
    /// The value shape observed at the read (helper rows demoted at capture
    /// sites keep their fragment/scalar kind).
    pub kind: crate::ValueKind,
    /// The disjunction of predicate conjunctions under which the read occurs.
    pub condition: GuardDnf,
    /// The resource containing the read site, for site-scoped read classes
    /// (condition, bound-value, templated-key, and rendered-effect reads);
    /// helper-internal reads carry none.
    pub resource: Option<ResourceRef>,
    /// Source sites justifying the read.
    pub provenance: Vec<ContractProvenance>,
    /// Whether the read belongs to the dependency lane (helper rows demoted
    /// at capture sites) instead of the document lane.
    pub dependency: bool,
}

/// Evaluate one template source into its abstract fragment.
pub(crate) fn eval_document(
    source: &str,
    source_path: Option<&str>,
    db: &IrAnalysisDb,
) -> EvaluatedDocument {
    let Some(tree) = parse_go_template(source) else {
        return EvaluatedDocument::default();
    };
    let document = TemplatedDocument::parse_with_root(source, tree.root_node());
    let mut interpreter = Interpreter::for_source(source, source_path, db, &tree, &document);
    let roots: Vec<NodeView<'_>> = document.roots().iter().map(NodeView::plain).collect();
    let contributions = interpreter.eval_node_list(&roots);
    EvaluatedDocument {
        root: contributions.assemble(),
        reads: interpreter.reads,
        type_hints: interpreter.type_hints,
        guarded_type_hints: interpreter.guarded_type_hints,
        fallback_type_hints: interpreter.fallback_type_hints,
        guarded_fallback_type_hints: interpreter.guarded_fallback_type_hints,
        shape_erased_paths: interpreter.shape_erased_paths,
        string_contract_paths: interpreter.string_contract_paths,
        range_modes: interpreter.range_modes,
        values_default_sources: interpreter.values_default_sources_observed,
        values_root_overlay_prefixes: interpreter.values_root_overlay_prefixes_observed,
        values_root_helper_includes: interpreter.values_root_helper_includes_observed,
        pre_rewrite_strict_paths: interpreter.pre_rewrite_strict_paths,
        fail_conditions: interpreter.fail_conditions,
    }
}

/// Control-header facts parsed once from the shared Go-template tree, keyed
/// by the region's opening-bracket byte (which equals the action node's
/// start byte).
pub(crate) struct ControlFacts {
    pub(super) header: Option<TemplateHeader>,
    pub(super) is_range: bool,
    pub(super) range_destructured: bool,
    /// The VALUE variable of a destructured range header (`$v` in
    /// `range $k, $v := …`).
    pub(super) range_value_variable: Option<String>,
    /// The KEY variable of a destructured range header (`$k` in
    /// `range $k, $v := …`).
    pub(super) range_key_variable: Option<String>,
    /// The whole region's end byte (through `{{ end }}`), for regions that
    /// only surface as holes (block-scalar bodies).
    pub(super) region_end: usize,
}

/// Source-only evaluation facts of one template body: independent of call
/// bindings, so helper bodies compute them once and reuse them across every
/// memoized-summary miss.
pub(crate) struct BodyEvalFacts {
    pub(super) control_facts: HashMap<usize, ControlFacts>,
    pub(super) resource_spans: Vec<ResourceSpan>,
}

impl BodyEvalFacts {
    pub(crate) fn collect(
        source: &str,
        db: &IrAnalysisDb,
        tree: &tree_sitter::Tree,
        document: &TemplatedDocument<'_>,
    ) -> Self {
        let mut control_facts = HashMap::new();
        collect_control_facts(tree.root_node(), source, &mut control_facts);
        Self {
            control_facts,
            resource_spans: crate::resource_identity::collect_resource_spans(document, db),
        }
    }
}

fn collect_control_facts(
    node: tree_sitter::Node<'_>,
    source: &str,
    out: &mut HashMap<usize, ControlFacts>,
) {
    match node.kind() {
        "if_action" | "with_action" => {
            out.insert(
                node.start_byte(),
                ControlFacts {
                    header: control_header(source, node),
                    is_range: false,
                    range_destructured: false,
                    range_value_variable: None,
                    range_key_variable: None,
                    region_end: node.end_byte(),
                },
            );
        }
        "range_action" => {
            out.insert(
                node.start_byte(),
                ControlFacts {
                    header: range_header_from_source(node, source),
                    is_range: true,
                    range_destructured: range_has_destructured_variable_definition(node),
                    range_value_variable: helm_schema_ast::range_destructured_value_variable(
                        node, source,
                    ),
                    range_key_variable: helm_schema_ast::range_destructured_key_variable(
                        node, source,
                    ),
                    region_end: node.end_byte(),
                },
            );
        }
        _ => {}
    }
    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        collect_control_facts(child, source, out);
    }
}

/// The byte where a container's first deeper *content* child appears (the
/// open-slot query's "mark": action lines, comments, and blanks are
/// transparent; only visible YAML lines deeper than the container mark it).
fn content_child_mark(children: &[Node], container_indent: usize) -> Option<usize> {
    children
        .iter()
        .filter_map(|child| match child {
            Node::Mapping(entry) if entry.indent > container_indent => Some(entry.span.start),
            Node::Sequence(item) if item.indent > container_indent => Some(item.span.start),
            Node::Scalar(line) if line.indent > container_indent => Some(line.span.start),
            _ => None,
        })
        .min()
}

fn collect_inline_regions(nodes: &[Node], out: &mut Vec<Span>) {
    for node in nodes {
        match node {
            Node::Opaque(opaque) if opaque.kind == OpaqueKind::InlineRegion => {
                out.push(opaque.span);
            }
            Node::Mapping(entry) => collect_inline_regions(&entry.children, out),
            Node::Sequence(item) => collect_inline_regions(&item.children, out),
            Node::Control(region) => {
                for branch in &region.branches {
                    collect_inline_regions(&branch.body, out);
                }
            }
            _ => {}
        }
    }
}

/// What one level of nodes contributes to its enclosing container.
#[derive(Default)]
pub(super) struct Contributions {
    pub(super) entries: Vec<MappingEntry>,
    pub(super) items: Vec<Guarded<AbstractFragment>>,
    pub(super) values: Guarded<AbstractFragment>,
    /// Fragment output carrying an explicit rendered indent
    /// (`… | nindent N`): it attaches to the nearest enclosing container
    /// whose indent is shallower than `N`, floating up past deeper open
    /// containers exactly like the attribution index's open-slot query.
    pub(super) floating: Vec<FloatingOutput>,
    pub(super) loop_control: LoopControl,
}

#[derive(Default)]
pub(super) struct LoopControl {
    pub(super) breaks: Vec<PathCondition>,
    pub(super) continues: Vec<PathCondition>,
}

impl LoopControl {
    pub(super) fn exit_condition(&self) -> PathCondition {
        any_conditions(self.breaks.iter().chain(&self.continues).cloned().collect())
    }

    pub(super) fn break_condition(&self) -> PathCondition {
        any_conditions(self.breaks.clone())
    }

    fn guard_all(&mut self, condition: &PathCondition) {
        for exit in self.breaks.iter_mut().chain(&mut self.continues) {
            *exit = and_conditions(condition.clone(), exit.clone());
        }
    }

    fn extend(&mut self, other: Self) {
        self.breaks.extend(other.breaks);
        self.continues.extend(other.continues);
    }
}

fn any_conditions(mut conditions: Vec<PathCondition>) -> PathCondition {
    conditions.retain(|condition| *condition != Predicate::False);
    if conditions.contains(&Predicate::True) {
        return Predicate::True;
    }
    conditions.sort();
    conditions.dedup();
    match conditions.as_slice() {
        [] => Predicate::False,
        [condition] => condition.clone(),
        _ => Predicate::Or(conditions),
    }
}

/// One explicitly-indented fragment output looking for its container.
pub(super) struct FloatingOutput {
    /// The rendered indent (`nindent`/`indent` width).
    pub(super) width: usize,
    /// The action's byte position (decides whether a same-indent container
    /// had already been "marked" by a deeper child when the output ran).
    pub(super) origin: usize,
    pub(super) value: Guarded<AbstractFragment>,
}

impl Contributions {
    pub(super) fn merge_entry(&mut self, key: EntryKey, value: Guarded<AbstractFragment>) {
        if let EntryKey::Literal(name) = &key
            && let Some(existing) = self.entries.iter_mut().find(
                |entry| matches!(&entry.key, EntryKey::Literal(existing_name) if existing_name == name),
            )
        {
            existing.value.extend(value);
            return;
        }
        self.entries.push(MappingEntry { key, value });
    }

    pub(super) fn push_value_arm(&mut self, arm: (PathCondition, AbstractFragment)) {
        self.values.arms.push(arm);
    }

    pub(super) fn guard_all(&mut self, condition: &PathCondition) {
        for entry in &mut self.entries {
            entry.value.guard_all(condition);
        }
        for item in &mut self.items {
            item.guard_all(condition);
        }
        self.values.guard_all(condition);
        for floating in &mut self.floating {
            floating.value.guard_all(condition);
        }
        self.loop_control.guard_all(condition);
    }

    pub(super) fn extend(&mut self, other: Self) {
        for entry in other.entries {
            self.merge_entry(entry.key, entry.value);
        }
        self.items.extend(other.items);
        self.values.extend(other.values);
        self.floating.extend(other.floating);
        self.loop_control.extend(other.loop_control);
    }

    pub(super) fn take_loop_control(&mut self) -> LoopControl {
        std::mem::take(&mut self.loop_control)
    }

    /// Split off the floating output that renders *inside* a container of
    /// the given indent, returning it as one guarded value; shallower output
    /// keeps floating for an ancestor. A container opened without an inline
    /// value also accepts output rendered at its own indent, unless a deeper
    /// child had already "marked" it before the output ran (both rules from
    /// the open-slot query).
    pub(super) fn take_floating_below(
        &mut self,
        container_indent: usize,
        accepts_same_indent: bool,
        marked_at: Option<usize>,
    ) -> Guarded<AbstractFragment> {
        let mut attached = Guarded::empty();
        let mut keep = Vec::new();
        for floating in std::mem::take(&mut self.floating) {
            let same_indent_ok = floating.width == container_indent
                && accepts_same_indent
                && marked_at.is_none_or(|marked| marked >= floating.origin);
            if floating.width > container_indent || same_indent_ok {
                attached.extend(floating.value);
            } else {
                keep.push(floating);
            }
        }
        self.floating = keep;
        attached
    }

    pub(super) fn assemble(self) -> Guarded<AbstractFragment> {
        let mut out = Guarded::empty();
        if !self.entries.is_empty() {
            out.arms.push((
                Predicate::True,
                AbstractFragment::Mapping(Mapping {
                    entries: self.entries,
                }),
            ));
        }
        if !self.items.is_empty() {
            out.arms.push((
                Predicate::True,
                AbstractFragment::Sequence(Sequence { items: self.items }),
            ));
        }
        out.extend(self.values);
        // Floating output that never found a shallower container attaches
        // at this level.
        for floating in self.floating {
            out.extend(floating.value);
        }
        out
    }
}

/// A node reference plus an optional adoption child limit: children whose
/// spans start at or beyond the limit belong *after* the adopting control
/// region (source order) and are evaluated there instead of inside the
/// branch scope.
#[derive(Clone, Copy)]
pub(super) struct NodeView<'n> {
    pub(super) node: &'n Node,
    pub(super) child_limit: Option<usize>,
}

impl<'n> NodeView<'n> {
    pub(super) fn plain(node: &'n Node) -> Self {
        Self {
            node,
            child_limit: None,
        }
    }

    /// The node's children that evaluate in place (before the child limit).
    /// The limit propagates so deeper descendants past it stay excluded too;
    /// the adopting control region re-attaches them outside its scope.
    pub(super) fn in_scope_children(&self) -> Vec<NodeView<'n>> {
        let children = match self.node {
            Node::Mapping(entry) => &entry.children,
            Node::Sequence(item) => &item.children,
            _ => return Vec::new(),
        };
        children
            .iter()
            .filter(|child| {
                self.child_limit
                    .is_none_or(|limit| child.span_start() < limit)
            })
            .map(|child| NodeView {
                node: child,
                child_limit: self.child_limit,
            })
            .collect()
    }
}

/// One adopted escaped sibling: its bounded in-scope view plus the
/// enclosing region bound that caps this region's deferral window.
pub(super) struct Adopted<'n> {
    pub(super) view: NodeView<'n>,
    pub(super) defer_upper: Option<usize>,
}

/// One arm's decoded activation.
pub(super) enum ArmSpec {
    If(Option<TemplateHeader>),
    With(Option<TemplateHeader>),
    Range {
        header: Option<TemplateHeader>,
        destructured: bool,
        value_variable: Option<String>,
        key_variable: Option<String>,
    },
    Else,
}

pub(super) struct Interpreter<'a> {
    pub(super) source: &'a str,
    pub(super) source_path: Option<&'a str>,
    /// Byte offset of this source within its file (helper bodies evaluate
    /// over the define body text; provenance spans stay file-absolute).
    pub(super) source_offset: usize,
    pub(super) db: &'a IrAnalysisDb,
    /// Source-only facts (control headers, resource spans), shared across
    /// the memoized evaluations of one helper body.
    pub(super) body_facts: Rc<BodyEvalFacts>,
    pub(super) inline_regions: Vec<Span>,
    /// Static file templates currently being inlined (cycle prevention for
    /// `.Files.Get`-style template requests).
    pub(super) inline_files: Vec<String>,
    /// Whether this interpreter evaluates a helper body (a summary run).
    pub(super) helper_scope: bool,
    /// The active helper call chain, threaded into expression evaluation so
    /// nested bound calls cut cycles.
    pub(super) helper_seen: HashSet<String>,
    pub(super) locals: SymbolicLocalState,
    pub(super) dot_stack: Vec<Option<AbstractValue>>,
    /// The value-flavor dot of a helper scope's root frame (the call
    /// boundary resolves both flavors; see `DotFrame`). Document scope has
    /// none: its value dot derives from the fragment dot.
    pub(super) root_value_dot: Option<AbstractValue>,
    pub(super) root_bindings: HashMap<String, AbstractValue>,
    pub(super) root_truthy_predicates: HashMap<String, Predicate>,
    /// Exhaustive per-arm value alternatives for root-context fields set
    /// across complete if/else chains (see [`RootValueDispatch`]); condition
    /// decoding resolves root-field equalities through them.
    pub(super) root_value_dispatches: HashMap<String, crate::eval_effect::RootValueDispatch>,
    /// Root-context replacements observed in source order and exported by helper summaries.
    pub(super) root_set_mutations_observed: BTreeMap<String, AbstractValue>,
    pub(super) root_set_predicates_observed: BTreeMap<String, Predicate>,
    pub(super) root_value_dispatches_observed:
        BTreeMap<String, crate::eval_effect::RootValueDispatch>,
    pub(super) values_default_sources_observed: BTreeSet<crate::ValuesDefaultSource>,
    pub(super) values_root_overlay_prefixes_observed: BTreeSet<String>,
    pub(super) values_root_helper_includes_observed: BTreeSet<String>,
    /// Values paths with a strict STRING consumer that executed before the
    /// first values-root program-wrapper rewrite in this source: a wrapper
    /// map at such a path reaches the consumer raw and aborts (nats'
    /// `fullname | trunc` reads `nameOverride` before `nats.defaultValues`
    /// substitutes the tplYaml result), so those nodes must not gain the
    /// wrapper alternative. Tolerant pre-rewrite reads (`default`
    /// selections that only copy the value) stay wrapper-eligible.
    pub(super) pre_rewrite_strict_paths: BTreeSet<String>,
    pub(super) active_predicates: Vec<Predicate>,
    /// Loop nesting depth of the evaluation point (block and inline range
    /// bodies): first-iteration reasoning is only sound at depth one.
    pub(super) loop_depth: usize,
    pub(super) reads: Vec<ValueRead>,
    /// Dedup shadow of `reads` (order lives in the vec).
    reads_seen: HashSet<ValueRead>,
    pub(super) type_hints: BTreeMap<String, BTreeSet<String>>,
    /// Paths consumed as serialized YAML by `fromYaml`; document-scope
    /// helper conditions import this narrow input contract without importing
    /// unrelated helper-body output transformations.
    pub(super) parsed_yaml_input_paths: BTreeSet<String>,
    /// Paths whose helper output was serialized with `toYaml`; callers use
    /// this to recognize a matching `fromYaml` as a structural round trip.
    pub(super) yaml_serialized_paths: BTreeSet<String>,
    /// Input-type hints observed while branch predicates were active: they
    /// hold only where those branches render, so they may type conditional
    /// overlays but never the unconditional base.
    pub(super) guarded_type_hints: BTreeMap<String, BTreeSet<String>>,
    /// Input-type hints from literal `default`/`coalesce` fallbacks: they
    /// type only the truthy arm of the path, never its Helm-falsy states.
    pub(super) fallback_type_hints: BTreeMap<String, BTreeSet<String>>,
    /// Fallback hints observed under branch predicates.
    pub(super) guarded_fallback_type_hints: BTreeMap<String, BTreeSet<String>>,
    /// Paths consumed only through total stringifications (`quote`,
    /// `toString`, `join`, `printf`): the chart tolerates any input type at
    /// them even when no placed row exists.
    pub(super) shape_erased_paths: BTreeSet<String>,
    /// Paths on which a string-consuming transform bound a real runtime
    /// string contract somewhere in the source.
    pub(super) string_contract_paths: BTreeSet<String>,
    /// The per-path range facts observed anywhere in this source (direct
    /// iteration, JSON-decoded values, key/value destructuring).
    pub(super) range_modes: crate::range_modes::RangeModes,
    /// `fail` captures (see [`FailCapture`]): no valid values document may
    /// satisfy one of these conjunctions.
    pub(super) fail_conditions: Vec<FailCapture>,
    /// Object-producing mutations observed before subsequent member reads.
    pub(super) member_host_conversions: BTreeSet<crate::eval_effect::MemberHostConversion>,
    /// Directly ranged paths active on the walk. Helper-scope ranges mark
    /// membership with truthy predicates (the summary lane's flavor), so
    /// fail capture re-adds the range facts from here.
    pub(super) active_direct_ranged_paths: Vec<String>,
    /// Approximate conjuncts for exact-range items that not every iterable
    /// alternative executes (nats' jsonpatch conditionally appends "from"
    /// to `$opPathKeys`). They condition CAPTURE conjunctions only — rows
    /// and type hints keep the join semantics ordinary contributions have —
    /// so strict captures inside such an item cannot bind unconditionally.
    pub(super) alternative_capture_approximates: Vec<Predicate>,
    /// Predicate paths severed by index-call narrowing anywhere in this
    /// source: guard reads of their strict ancestors are dropped from the
    /// summary (the narrowing proves the ancestor probe was a traversal
    /// step, not a condition on the ancestor itself).
    pub(super) suppress_predicate_paths: BTreeSet<String>,
    /// Every chart-level `set … default` normalization observed anywhere in
    /// this source, unconditionally. `locals.chart_value_defaults` keeps the
    /// branch-intersected "definitely ran in source order" view for render
    /// sites; helper summaries export this accumulator instead (a summary's
    /// defaults are declarations for the caller, like they always were).
    pub(super) chart_defaults_observed: BTreeSet<String>,
    /// The site facts of the hole or control region currently being
    /// evaluated; reads recorded during that evaluation carry them.
    pub(super) current_site: Option<Rc<SiteFacts>>,
}

impl<'a> Interpreter<'a> {
    /// A fresh interpreter over one parsed source: control-header facts,
    /// inline-region spans, and resource spans are collected up front; all
    /// evaluation state starts empty.
    pub(super) fn for_source(
        source: &'a str,
        source_path: Option<&'a str>,
        db: &'a IrAnalysisDb,
        tree: &tree_sitter::Tree,
        document: &TemplatedDocument<'_>,
    ) -> Self {
        let body_facts = Rc::new(BodyEvalFacts::collect(source, db, tree, document));
        Self::with_body_facts(source, source_path, db, document, body_facts)
    }

    /// A fresh interpreter reusing precomputed source-only facts (helper
    /// bodies share them across memoized evaluations).
    pub(super) fn with_body_facts(
        source: &'a str,
        source_path: Option<&'a str>,
        db: &'a IrAnalysisDb,
        document: &TemplatedDocument<'_>,
        body_facts: Rc<BodyEvalFacts>,
    ) -> Self {
        let mut inline_regions = Vec::new();
        collect_inline_regions(document.roots(), &mut inline_regions);
        Self {
            source,
            source_path,
            source_offset: 0,
            db,
            body_facts,
            inline_regions,
            inline_files: Vec::new(),
            helper_scope: false,
            helper_seen: HashSet::new(),
            locals: SymbolicLocalState::default(),
            dot_stack: Vec::new(),
            root_value_dot: None,
            root_bindings: HashMap::new(),
            root_truthy_predicates: HashMap::new(),
            root_value_dispatches: HashMap::new(),
            root_set_mutations_observed: BTreeMap::new(),
            root_set_predicates_observed: BTreeMap::new(),
            root_value_dispatches_observed: BTreeMap::new(),
            values_default_sources_observed: BTreeSet::new(),
            values_root_overlay_prefixes_observed: BTreeSet::new(),
            values_root_helper_includes_observed: BTreeSet::new(),
            pre_rewrite_strict_paths: BTreeSet::new(),
            active_predicates: Vec::new(),
            loop_depth: 0,
            reads: Vec::new(),
            reads_seen: HashSet::new(),
            type_hints: BTreeMap::new(),
            parsed_yaml_input_paths: BTreeSet::new(),
            yaml_serialized_paths: BTreeSet::new(),
            guarded_type_hints: BTreeMap::new(),
            fallback_type_hints: BTreeMap::new(),
            guarded_fallback_type_hints: BTreeMap::new(),
            shape_erased_paths: BTreeSet::new(),
            string_contract_paths: BTreeSet::new(),
            range_modes: crate::range_modes::RangeModes::default(),
            fail_conditions: Vec::new(),
            member_host_conversions: BTreeSet::new(),
            active_direct_ranged_paths: Vec::new(),
            alternative_capture_approximates: Vec::new(),
            suppress_predicate_paths: BTreeSet::new(),
            chart_defaults_observed: BTreeSet::new(),
            current_site: None,
        }
    }

    pub(super) fn text(&self, span: Span) -> &'a str {
        self.source.get(span.start..span.end).unwrap_or("")
    }

    /// The site facts of one output hole: the smallest resource span
    /// containing the hole's start byte plus the hole's own provenance.
    pub(super) fn hole_site(&self, span: Span) -> Option<Rc<SiteFacts>> {
        let resource_span = self
            .body_facts
            .resource_spans
            .iter()
            .filter(|resource| resource.start <= span.start && span.start < resource.end)
            .min_by(|left, right| {
                let left_len = left.end.saturating_sub(left.start);
                let right_len = right.end.saturating_sub(right.start);
                left_len
                    .cmp(&right_len)
                    .then_with(|| right.start.cmp(&left.start))
            });
        self.site_facts(resource_span.map(|span| self.span_resource(span)), span)
    }

    /// The site facts of one control region: the region's resource is the
    /// unique resource intersecting the region span (a region spanning
    /// several manifest documents claims none).
    pub(super) fn region_site(&self, span: Span) -> Option<Rc<SiteFacts>> {
        let mut unique: Option<&ResourceSpan> = None;
        for resource in &self.body_facts.resource_spans {
            if resource.start >= span.end || span.start >= resource.end {
                continue;
            }
            match unique {
                Some(existing) if existing.resource != resource.resource => {
                    unique = None;
                    break;
                }
                Some(_) => {}
                None => unique = Some(resource),
            }
        }
        self.site_facts(unique.map(|span| self.span_resource(span)), span)
    }

    /// The span's resource for one tagged use, with any inline-conditional
    /// kind arms predicate-qualified through the CURRENT scope: the
    /// selecting locals bind above the header, so each guard lowers exactly
    /// as the body's own branch conditions do and the builder can match row
    /// conjunctions to arms structurally.
    fn span_resource(&self, resource_span: &ResourceSpan) -> (ResourceRef, Vec<String>) {
        let mut resource = resource_span.resource.clone();
        resource.kind_branches = self.resolved_kind_branches(&resource_span.kind_branch_sources);
        (resource, resource_span.path_prefix.clone())
    }

    /// Lower an inline kind chain's raw guard texts into per-arm
    /// predicates. An arm holds where its own guard does AND every earlier
    /// guard failed. Any undecodable guard abstains entirely: dropping one
    /// arm would leave an incomplete partition that misassigns rows.
    fn resolved_kind_branches(
        &self,
        sources: &[helm_schema_ast::KindBranchSource],
    ) -> Vec<helm_schema_core::KindBranch> {
        if sources.is_empty() {
            return Vec::new();
        }
        let context = self.value_path_context();
        let mut prior_negations: Vec<Predicate> = Vec::new();
        let mut branches = Vec::new();
        for source in sources {
            let mut conjuncts = prior_negations.clone();
            if let Some(text) = &source.condition {
                let wrapped = format!("{{{{ {} }}}}", text.trim());
                let exprs = helm_schema_ast::parse_action_expressions(&wrapped);
                let [expr] = exprs.as_slice() else {
                    return Vec::new();
                };
                if !context.condition_lowering_is_faithful(expr) {
                    return Vec::new();
                }
                let predicate = context.condition_predicate_expr(expr);
                prior_negations.push(predicate.negated());
                conjuncts.push(predicate);
            }
            branches.push(helm_schema_core::KindBranch {
                predicate: Predicate::all(conjuncts),
                kind: source.kind.clone(),
            });
        }
        branches
    }

    fn site_facts(
        &self,
        resource: Option<(ResourceRef, Vec<String>)>,
        span: Span,
    ) -> Option<Rc<SiteFacts>> {
        let provenance = self.source_path.map(|source_path| {
            let helper_chain = self
                .inline_files
                .iter()
                .filter_map(|entry| entry.strip_prefix("define:"))
                .map(std::string::ToString::to_string)
                .collect();
            ContractProvenance::new(
                source_path,
                SourceSpan::new(
                    self.source_offset + span.start,
                    self.source_offset + span.end,
                ),
                helper_chain,
            )
        });
        let (resource, path_prefix) = match resource {
            Some((resource, path_prefix)) => (Some(resource), path_prefix),
            None => (None, Vec::new()),
        };
        if resource.is_none() && provenance.is_none() {
            return None;
        }
        Some(Rc::new(SiteFacts {
            resource,
            path_prefix,
            provenance,
        }))
    }

    /// Run one evaluation step under the site facts of `span`, restoring the
    /// previous site afterwards.
    pub(super) fn enter_hole_site(&mut self, span: Span) -> Option<Rc<SiteFacts>> {
        let site = self.hole_site(span);
        std::mem::replace(&mut self.current_site, site)
    }

    pub(super) fn restore_site(&mut self, previous: Option<Rc<SiteFacts>>) {
        self.current_site = previous;
    }

    pub(super) fn current_dot_fragment(&self) -> Option<AbstractValue> {
        self.dot_stack.last().cloned().flatten()
    }

    pub(super) fn current_dot_binding(&self) -> Option<AbstractValue> {
        if self.dot_stack.len() <= 1
            && let Some(root) = &self.root_value_dot
        {
            return Some(root.clone());
        }
        self.dot_stack
            .last()
            .and_then(|binding| binding.as_ref())
            .and_then(AbstractValue::to_current_dot_context_value)
    }

    /// The value-flavor dot for expression evaluation: a helper scope's root
    /// frame carries the call boundary's own value dot; everywhere else the
    /// fragment dot's context-value projection stands in.
    pub(super) fn current_value_dot(&self) -> Option<AbstractValue> {
        if self.dot_stack.len() <= 1
            && let Some(root) = &self.root_value_dot
        {
            return Some(root.clone());
        }
        self.current_dot_fragment()
            .map(|value| value.to_context_value())
            .or_else(|| self.current_dot_binding())
    }

    pub(super) fn value_path_context(&self) -> ValuePathContext<'_> {
        // Member bindings resolve for conditions and assignments; explicit
        // fragment values shadow them where both exist.
        let mut template_bindings = self.locals.range_member_values.clone();
        template_bindings.extend(
            self.locals
                .fragment_values
                .iter()
                .map(|(name, value)| (name.clone(), value.clone())),
        );
        ValuePathContext {
            root_bindings: &self.root_bindings,
            root_truthy_predicates: &self.root_truthy_predicates,
            root_value_dispatches: &self.root_value_dispatches,
            template_bindings,
            range_domains: &self.locals.range_domains,
            get_bindings: &self.locals.get_bindings,
            template_default_paths: &self.locals.default_paths,
            template_output_meta: &self.locals.output_meta,
            template_truthy_reductions: &self.locals.truthy_reductions,
            typeof_bindings: &self.locals.typeof_sources,
            int_cast_bindings: &self.locals.int_cast_sources,
            kube_version_bindings: &self.locals.kube_version_sources,
            fragment_context: FragmentEvalContext::new(self.db),
            current_dot_fragment: self.current_dot_fragment(),
            current_dot_binding: self.current_value_dot(),
        }
    }

    /// Record that rendering FAILS unconditionally under the currently
    /// active predicates (`fail` calls): no valid values document may
    /// satisfy them. The RAW predicates are kept — the guard-DNF
    /// conversion drops conjuncts it cannot represent, which negation
    /// cannot tolerate.
    pub(super) fn record_fail_condition(&mut self) {
        let capture = FailCapture {
            conjunction: self.fail_capture_conjunction(Vec::new()),
            ranged: self.capture_ranged_modes(),
            kind: CaptureKind::Fail,
        };
        if capture
            .conjunction
            .iter()
            .any(|p| matches!(p, Predicate::False))
        {
            return;
        }
        if !self.fail_conditions.contains(&capture) {
            self.fail_conditions.push(capture);
        }
    }

    /// Record a `required(message, subject)` guardrail: rendering fails
    /// under the ambient predicates whenever the subject is Helm-empty
    /// (absent, null, or the empty string).
    pub(super) fn record_required_condition(&mut self, subject_path: &str) {
        let empty = Predicate::Or(vec![
            Predicate::from(Guard::Absent {
                path: subject_path.to_string(),
            }),
            Predicate::from(Guard::Eq {
                path: subject_path.to_string(),
                value: helm_schema_core::GuardValue::Null,
            }),
            Predicate::from(Guard::Eq {
                path: subject_path.to_string(),
                value: helm_schema_core::GuardValue::string(""),
            }),
        ]);
        let capture = FailCapture {
            conjunction: self.fail_capture_conjunction(vec![empty]),
            ranged: self.capture_ranged_modes(),
            kind: CaptureKind::Fail,
        };
        if capture
            .conjunction
            .iter()
            .any(|p| matches!(p, Predicate::False))
        {
            return;
        }
        if !self.fail_conditions.contains(&capture) {
            self.fail_conditions.push(capture);
        }
    }

    /// The ambient predicates plus `tail`, with active direct range facts
    /// present even when a caller constructed the capture indirectly.
    pub(super) fn fail_capture_conjunction(&self, tail: Vec<Predicate>) -> Vec<Predicate> {
        let mut conjunction = self.active_predicates.clone();
        for path in &self.active_direct_ranged_paths {
            let range = Predicate::from(Guard::Range { path: path.clone() });
            if !conjunction.contains(&range) {
                conjunction.push(range);
            }
        }
        for approximate in &self.alternative_capture_approximates {
            if !conjunction.contains(approximate) {
                conjunction.push(approximate.clone());
            }
        }
        conjunction.extend(tail);
        conjunction
    }

    /// The range facts a fail capture rides: paths actively ranged at the
    /// capture site are `direct` (only these have member identities), while
    /// the JSON-decoded and destructured flavors carry every occurrence
    /// observed in this source.
    pub(super) fn capture_ranged_modes(&self) -> crate::range_modes::RangeModes {
        let mut ranged = crate::range_modes::RangeModes::default();
        for path in &self.active_direct_ranged_paths {
            ranged.mark_direct(path);
        }
        for (path, mode) in self.range_modes.iter() {
            if mode.json_decoded {
                ranged.mark_json_decoded(path);
            }
            if mode.destructured {
                ranged.mark_destructured(path);
            }
        }
        ranged
    }

    pub(super) fn ambient_condition(&self) -> GuardDnf {
        GuardDnf::from_conjunction(self.active_predicates.iter().cloned())
    }

    pub(super) fn push_predicate(&mut self, predicate: Predicate) {
        // `False` is load-bearing: a decoded-dead branch (a `hasKey` probe
        // into a folded literal table that misses) must poison the captures
        // recorded under it. Only `True` is skippable noise.
        if !matches!(predicate, Predicate::True) && !self.active_predicates.contains(&predicate) {
            self.active_predicates.push(predicate);
        }
    }

    /// Whether an enclosing condition's lowering is APPROXIMATE (truthy
    /// fallbacks, dropped conjuncts). Activation pushes the approximation
    /// onto the predicate stack as a [`Predicate::Approximate`] conjunct
    /// (later arms carry it inside the negated prior), so scanning the
    /// active predicates sees exactly the enclosing approximations. Rows
    /// tolerate wider conditions; string-contract metadata and fail
    /// NEGATION abstain under one.
    pub(super) fn under_approximate_condition(&self) -> bool {
        self.active_predicates
            .iter()
            .any(Predicate::contains_approximation)
    }

    /// A site-scoped pathless read: condition operands, bound-value reads,
    /// templated-key splices, and rendered-effect reads carry the current
    /// site's resource and provenance (the same scoping the emission
    /// terminal applied to their rows).
    pub(super) fn push_read(&mut self, values_path: &str, extra_guards: &[Guard]) {
        let (resource, provenance) = match &self.current_site {
            Some(site) => (
                site.resource.clone(),
                site.provenance.iter().cloned().collect(),
            ),
            None => (None, Vec::new()),
        };
        self.push_read_row(
            values_path,
            crate::ValueKind::Scalar,
            extra_guards,
            resource,
            provenance,
            false,
        );
    }

    pub(super) fn push_read_row(
        &mut self,
        values_path: &str,
        kind: crate::ValueKind,
        extra_guards: &[Guard],
        resource: Option<ResourceRef>,
        provenance: Vec<ContractProvenance>,
        dependency: bool,
    ) {
        let condition = self
            .ambient_condition()
            .conjoined_with_guards(extra_guards.iter().cloned());
        self.push_read_row_with_condition(
            values_path,
            kind,
            condition,
            resource,
            provenance,
            dependency,
        );
    }

    fn push_read_row_with_condition(
        &mut self,
        values_path: &str,
        kind: crate::ValueKind,
        condition: GuardDnf,
        resource: Option<ResourceRef>,
        provenance: Vec<ContractProvenance>,
        dependency: bool,
    ) {
        if values_path.trim().is_empty() {
            return;
        }
        let read = ValueRead {
            values_path: values_path.to_string(),
            kind,
            condition,
            resource,
            provenance,
            dependency,
        };
        if self.reads_seen.insert(read.clone()) {
            self.reads.push(read);
        }
    }

    /// Absorb one nested interpreter's read verbatim (nested static-file
    /// evaluations already stamped their own guards and sites).
    pub(super) fn push_nested_read(&mut self, read: ValueRead) {
        if self.reads_seen.insert(read.clone()) {
            self.reads.push(read);
        }
    }

    /// Pathless reads for the splices of a templated mapping key. Keys have
    /// no guarded arms in the tree, so their reads are recorded at the eval
    /// site where the ambient predicates (branch and range conditions) are
    /// still active; the projection deliberately does not re-derive them.
    pub(super) fn push_key_reads(&mut self, key: &EntryKey) {
        let EntryKey::Dynamic(string) = key else {
            return;
        };
        for part in &string.parts {
            match part {
                StringPart::Text(_) => {}
                // A rendered RANGE KEY in a templated key says nothing about
                // the collection's VALUE domain.
                StringPart::Splice(splice) if splice.meta.range_key => {}
                StringPart::Splice(splice) => {
                    let mut extra = Vec::new();
                    if splice.meta.defaulted {
                        extra.push(Guard::Default {
                            path: splice.values_path.clone(),
                        });
                    }
                    // A key position formats every SCALAR (a numeric label
                    // key renders `7:` and YAML-to-JSON stringifies it), so
                    // the read carries the partial-scalar kind: a declared
                    // string default widens to the scalar union instead of
                    // pinning the raw input as a string.
                    let (resource, provenance) = match &self.current_site {
                        Some(site) => (
                            site.resource.clone(),
                            site.provenance.iter().cloned().collect(),
                        ),
                        None => (None, Vec::new()),
                    };
                    self.push_read_row(
                        &splice.values_path,
                        crate::ValueKind::PartialScalar,
                        &extra,
                        resource,
                        provenance,
                        false,
                    );
                }
                StringPart::Taint(taint) => {
                    for path in &taint.paths {
                        self.push_read(path, &[]);
                    }
                }
            }
        }
    }

    /// Pathless reads for a helper meta row retain its predicate disjunction
    /// as one condition. Helper rows have no site resource; their provenance
    /// is the read site's plus the helper body sites recorded in the meta.
    pub(super) fn push_meta_reads(
        &mut self,
        values_path: &str,
        kind: crate::ValueKind,
        meta: &HelperOutputMeta,
        sibling_claims: &BTreeSet<String>,
        dependency: bool,
    ) {
        let helper_condition = if meta.predicates.is_empty() {
            GuardDnf::unconditional()
        } else {
            GuardDnf::from_disjunction(meta.predicates.iter().map(|branch| branch.iter().cloned()))
        };
        let mut provenance: Vec<ContractProvenance> = self
            .current_site
            .as_ref()
            .and_then(|site| site.provenance.clone())
            .into_iter()
            .collect();
        merge_provenance_sites(&mut provenance, &meta.provenance);
        let mut condition = self
            .claim_scoped_ambient_condition(values_path, sibling_claims)
            .conjoined(&helper_condition);
        if meta.defaulted {
            condition = condition.conjoined_with_guards([Guard::Default {
                path: values_path.to_string(),
            }]);
        }
        self.push_read_row_with_condition(
            values_path,
            kind,
            condition,
            None,
            provenance,
            dependency,
        );
    }

    /// The ambient condition scoped to one helper claim: a truthiness
    /// condition about a *different* claim path of the same call describes a
    /// sibling's branch, not this row's, and is dropped unless the paths are
    /// related (the summary lane's sibling-source rule).
    fn claim_scoped_ambient_condition(
        &self,
        claim_path: &str,
        sibling_claims: &BTreeSet<String>,
    ) -> GuardDnf {
        if !self.helper_scope {
            return GuardDnf::from_conjunction(self.active_predicates.iter().cloned());
        }
        GuardDnf::from_conjunction(
            self.active_predicates
                .iter()
                .filter(|predicate| {
                    let path = match predicate {
                        Predicate::Guard(Guard::Truthy { path }) => path,
                        Predicate::Not(inner) => match inner.as_ref() {
                            Predicate::Guard(Guard::Truthy { path }) => path,
                            _ => return true,
                        },
                        _ => return true,
                    };
                    path == claim_path
                        || !sibling_claims.contains(path)
                        || crate::helper_meta::values_paths_are_related(path, claim_path)
                })
                .cloned(),
        )
    }

    /// Absorb helper-body reads at a call site: each read keeps its
    /// helper-internal guards and gains the site's ambient guards; the
    /// site's provenance leads the read's helper-body sites. Helper-internal
    /// reads carry no resource of their own, so site-less rows stay
    /// resource-free exactly like the summary lane always was.
    /// Absorb called-helper fail conjunctions: the body recorded its
    /// internal predicates; the call site prepends its ambient predicates,
    /// the same scoping helper reads get.
    /// Values paths a strict STRING consumer captured so far, regardless
    /// of branch scope: a program-wrapper map reaching such a consumer raw
    /// aborts rendering (`trunc`/`contains` type-assert strings, and a
    /// wrapper map is truthy, so even self-guarded consumers run). The
    /// pre-rewrite wrapper-exclusion snapshot reads this — conditional
    /// captures count because engines guard their whole body with an
    /// idempotence flag exactly as conditional as the rewrite itself.
    pub(super) fn strict_string_capture_paths(&self) -> BTreeSet<String> {
        let mut paths = self.string_contract_paths.clone();
        for capture in &self.fail_conditions {
            match &capture.kind {
                crate::eval_effect::CaptureKind::ValueType { path, schema_type }
                    if schema_type == "string" =>
                {
                    paths.insert(path.clone());
                }
                crate::eval_effect::CaptureKind::ValuePattern { path, .. } => {
                    paths.insert(path.clone());
                }
                _ => {}
            }
        }
        paths.retain(|path| !path.trim().is_empty() && !path.contains('*'));
        paths
    }

    pub(super) fn absorb_helper_fails(&mut self, fails: &[FailCapture]) {
        for body_capture in fails {
            let mut ranged = self.capture_ranged_modes();
            ranged.merge(&body_capture.ranged);
            let conjunction = self.fail_capture_conjunction(body_capture.conjunction.clone());
            let mut kind = body_capture.kind.clone();
            if let CaptureKind::MemberAccess { handled_kinds } = &mut kind {
                let target = conjunction.iter().find_map(|predicate| match predicate {
                    Predicate::Not(inner) => match inner.as_ref() {
                        Predicate::Guard(Guard::TypeIs { path, schema_type })
                            if schema_type == "object" =>
                        {
                            Some(path)
                        }
                        _ => None,
                    },
                    _ => None,
                });
                if let Some(target) = target {
                    handled_kinds.extend(
                        self.member_host_conversions
                            .iter()
                            .filter(|conversion| {
                                &conversion.path == target
                                    && conversion
                                        .outer_predicates
                                        .iter()
                                        .all(|predicate| conjunction.contains(predicate))
                            })
                            .map(|conversion| conversion.input_kind.clone()),
                    );
                }
            }
            let capture = FailCapture {
                conjunction,
                ranged,
                kind,
            };
            if capture
                .conjunction
                .iter()
                .any(|p| matches!(p, Predicate::False))
            {
                continue;
            }
            if !self.fail_conditions.contains(&capture) {
                self.fail_conditions.push(capture);
            }
        }
    }

    pub(super) fn absorb_helper_reads_with_suppression(
        &mut self,
        reads: &[ValueRead],
        suppressed: &BTreeSet<&String>,
        sibling_claims: &BTreeSet<String>,
    ) {
        let site_provenance: Vec<ContractProvenance> = self
            .current_site
            .as_ref()
            .and_then(|site| site.provenance.clone())
            .into_iter()
            .collect();
        for read in reads {
            // Guard-path reads that are strict ancestors of a predicate path
            // the helper explicitly severed (index-call narrowing) are
            // dropped, the same way the summary lane always skipped them.
            if !read.dependency
                && !suppressed.contains(&read.values_path)
                && suppressed.iter().any(|narrowed| {
                    helm_schema_core::values_path_is_descendant(narrowed, &read.values_path)
                })
            {
                continue;
            }
            let mut provenance = site_provenance.clone();
            merge_provenance_sites(&mut provenance, &read.provenance);
            let condition = self
                .claim_scoped_ambient_condition(&read.values_path, sibling_claims)
                .conjoined(&read.condition);
            self.push_read_row_with_condition(
                &read.values_path,
                read.kind,
                condition,
                read.resource.clone(),
                provenance,
                read.dependency,
            );
        }
    }

    pub(super) fn eval_node_list(&mut self, nodes: &[NodeView<'_>]) -> Contributions {
        // The CST appends children escaping an ill-nested region at
        // container-close time, which can put them before the region in list
        // order; span order is document order, and adoption depends on it.
        let mut ordered: Vec<NodeView<'_>> = nodes.to_vec();
        ordered.sort_by_key(|view| view.node.span_start());
        let nodes = &ordered;
        let mut out = Contributions::default();
        let mut index = 0;
        let mut remaining = Predicate::True;
        while let Some(view) = nodes.get(index) {
            if remaining == Predicate::False {
                break;
            }
            let entry_predicates = self.active_predicates.len();
            self.push_predicate(remaining.clone());
            let mut next = Contributions::default();
            match view.node {
                Node::Control(region) => {
                    // Re-adopt siblings that escaped an ill-nested region:
                    // their spans still lie inside the region, so they belong
                    // to a branch body (with its guards and dot bindings).
                    // Children of an adopted node that start after the region
                    // end stay outside its scope via the child limit.
                    let region_index = index;
                    let mut adopted = Vec::new();
                    while let Some(next) = nodes.get(index + 1) {
                        if next.node.span_start() < region.span.end {
                            // In-scope evaluation is bounded by the innermost
                            // region end; deferral hands descendants past this
                            // region (but within the enclosing bound) back to
                            // this region, and the rest to the enclosing one.
                            let in_scope = next
                                .child_limit
                                .map_or(region.span.end, |limit| limit.min(region.span.end));
                            adopted.push(Adopted {
                                view: NodeView {
                                    node: next.node,
                                    child_limit: Some(in_scope),
                                },
                                defer_upper: next.child_limit,
                            });
                            index += 1;
                        } else {
                            break;
                        }
                    }
                    // Descendants of *earlier* siblings that escaped forward
                    // into the region (a branch contributing to a container
                    // opened before it) belong to branch bodies too; their
                    // in-place evaluation was bounded at the region start.
                    let mut escaped = Vec::new();
                    for prior in nodes.get(..region_index).unwrap_or_default() {
                        if matches!(prior.node, Node::Control(_)) {
                            continue;
                        }
                        let mut chain = Vec::new();
                        super::control::collect_deferred(
                            prior.node,
                            region.span.start,
                            prior.child_limit,
                            &mut chain,
                            &mut escaped,
                        );
                    }
                    next.extend(self.eval_control(region, &adopted, escaped));
                }
                Node::Output(action) => {
                    let consumed = self.eval_output_with_lookahead(action, nodes, index, &mut next);
                    index += consumed;
                }
                _ => {
                    // Evaluation stops at the next control sibling's start:
                    // descendants escaping into that region evaluate inside
                    // its branches instead of unguarded in place.
                    let mut bounded = *view;
                    if let Some(region_start) = nodes
                        .get(index + 1..)
                        .into_iter()
                        .flatten()
                        .find_map(|next| match next.node {
                            Node::Control(region) => Some(region.span.start),
                            _ => None,
                        })
                    {
                        bounded.child_limit = Some(
                            bounded
                                .child_limit
                                .map_or(region_start, |limit| limit.min(region_start)),
                        );
                    }
                    next.extend(self.eval_node(bounded));
                }
            }
            self.active_predicates.truncate(entry_predicates);
            let exit_condition = next.loop_control.exit_condition();
            next.guard_all(&remaining);
            out.extend(next);
            remaining = match exit_condition {
                Predicate::False => remaining,
                Predicate::True => Predicate::False,
                exit => and_conditions(remaining, exit.negated()),
            };
            index += 1;
        }
        out
    }

    /// Evaluate a standalone output action, recognizing the templated
    /// mapping-key line shape (`{{ key-expr }}: value…`) from the trailing
    /// action-line text node. Returns how many extra sibling nodes were
    /// consumed.
    fn eval_output_with_lookahead(
        &mut self,
        action: &syntax::OutputAction,
        nodes: &[NodeView<'_>],
        index: usize,
        out: &mut Contributions,
    ) -> usize {
        let key_line = nodes.get(index + 1).and_then(|next| match next.node {
            Node::Opaque(opaque) if opaque.kind == OpaqueKind::ActionLineText => {
                let text = self.text(opaque.span);
                syntax::structural_mapping_colon(text).map(|colon| {
                    (
                        opaque.span,
                        text.get(..colon).unwrap_or("").to_string(),
                        text.get(colon + 1..).unwrap_or("").to_string(),
                    )
                })
            }
            _ => None,
        });
        let Some((text_span, key_suffix, rest)) = key_line else {
            let (value, width) = self.eval_output_action(action.span);
            match width {
                Some(width) => out.floating.push(FloatingOutput {
                    width,
                    origin: action.span.start,
                    value,
                }),
                None => out.values.extend(value),
            }
            return 0;
        };

        // `{{ key }}…: …` — a dynamic mapping entry: the action (plus any
        // literal key suffix before the structural colon) is the key; the
        // inline value is the literal text after the colon or a same-line
        // action.
        let previous_site = self.enter_hole_site(action.span);
        let mut key_string = self.hole_string(action.span);
        if !key_suffix.is_empty() {
            key_string
                .parts
                .push(StringPart::Text([key_suffix].into_iter().collect()));
        }
        let key = EntryKey::Dynamic(key_string);
        self.push_key_reads(&key);
        self.restore_site(previous_site);
        let mut consumed = 1;
        let value = if rest.trim().is_empty() {
            match nodes.get(index + 2).map(|view| view.node) {
                Some(Node::Output(value_action))
                    if self.same_line(text_span.end, value_action.span.start) =>
                {
                    consumed = 2;
                    self.eval_entire_hole(value_action.span)
                }
                _ => Guarded::empty(),
            }
        } else if rest.trim().starts_with('|') || rest.trim().starts_with('>') {
            // `{{ key }}…: |` — a block scalar under a templated key. The
            // layout cannot open a block frame for templated keys, so the
            // body arrives as deeper-indented sibling lines; consume them as
            // the entry's render-suppressed blob.
            let key_indent = self.line_indent(action.span.start);
            let (block, block_consumed) =
                self.consume_dynamic_block_body(nodes, index + 2, key_indent);
            consumed += block_consumed;
            block
        } else {
            Guarded::unconditional(AbstractFragment::Scalar(AbstractString::literal(
                rest.trim().to_string(),
            )))
        };
        out.merge_entry(key, value);
        consumed
    }

    /// Consume the deeper-indented sibling lines forming the body of a
    /// templated-key block scalar, evaluating their holes as suppressed
    /// parts. Returns the suppressed scalar and how many nodes were
    /// consumed.
    fn consume_dynamic_block_body(
        &mut self,
        nodes: &[NodeView<'_>],
        start_index: usize,
        key_indent: usize,
    ) -> (Guarded<AbstractFragment>, usize) {
        let mut parts: Vec<StringPart> = Vec::new();
        let mut consumed = 0;
        while let Some(next) = nodes.get(start_index + consumed) {
            let node = next.node;
            if self.line_indent(node.span_start()) <= key_indent {
                break;
            }
            match node {
                Node::Output(action) => {
                    for (_, hole_parts) in self.eval_hole_parts(action.span) {
                        parts.extend(hole_parts);
                    }
                }
                Node::Scalar(line) => {
                    for part in &line.content.parts {
                        match part {
                            ScalarPart::Text(span) => {
                                let text = self.text(*span);
                                if !text.is_empty() {
                                    parts.push(StringPart::Text(
                                        [text.to_string()].into_iter().collect(),
                                    ));
                                }
                            }
                            ScalarPart::Hole(span) => {
                                for (_, hole_parts) in self.eval_hole_parts(*span) {
                                    parts.extend(hole_parts);
                                }
                            }
                        }
                    }
                }
                Node::Opaque(opaque) if opaque.kind == OpaqueKind::ActionLineText => {
                    let text = self.text(opaque.span);
                    if !text.is_empty() {
                        parts.push(StringPart::Text([text.to_string()].into_iter().collect()));
                    }
                }
                _ => break,
            }
            consumed += 1;
        }
        let value = Guarded::unconditional(AbstractFragment::Scalar(AbstractString {
            parts,
            suppressed: true,
        }));
        (value, consumed)
    }

    fn same_line(&self, from: usize, to: usize) -> bool {
        self.source
            .get(from..to)
            .is_some_and(|between| !between.contains('\n') && between.trim().is_empty())
    }

    /// The rendered indent of a templated mapping-entry line (the key
    /// hole's explicit `nindent` width when present, else the line indent).
    pub(super) fn dynamic_entry_render_indent(&self, span: Span) -> usize {
        let line_start = self
            .source
            .get(..span.start)
            .and_then(|prefix| prefix.rfind('\n'))
            .map_or(0, |newline| newline + 1);
        let line_end = self
            .source
            .get(span.start..)
            .and_then(|rest| rest.find('\n'))
            .map_or(self.source.len(), |offset| span.start + offset);
        let line = self.source.get(line_start..line_end).unwrap_or("");
        for expr in helm_schema_ast::parse_action_expressions(line) {
            if let Some(width) = expr.fragment_indent_width() {
                return width;
            }
        }
        self.line_indent(span.start)
    }

    /// The structural indent of one node: containers report their own
    /// indent, scalars their line indent, plain outputs their line indent,
    /// and control regions the minimum over their branch bodies (a region's
    /// rendered content sits at the body indent; the header line is
    /// conventionally unindented). Outputs with an explicit rendered indent
    /// (`… | nindent N`) report `None`: they float, and the float rules own
    /// their placement (line columns are layout noise for them).
    pub(super) fn structural_content_indent(&self, node: &Node) -> Option<usize> {
        match node {
            Node::Mapping(entry) => Some(entry.indent),
            Node::Sequence(item) => Some(item.indent),
            Node::Scalar(line) => Some(line.indent),
            Node::Control(region) => region
                .branches
                .iter()
                .flat_map(|branch| &branch.body)
                .filter_map(|child| self.structural_content_indent(child))
                .min(),
            Node::Output(action) => {
                let width = parse_expr_text(self.text(action.span))
                    .iter()
                    .rev()
                    .find_map(TemplateExpr::fragment_indent_width);
                match width {
                    Some(_) => None,
                    None => Some(self.line_indent(action.span.start)),
                }
            }
            Node::Comment(_) | Node::Opaque(_) => None,
        }
    }

    /// The indentation of the line containing `byte`.
    pub(super) fn line_indent(&self, byte: usize) -> usize {
        let line_start = self
            .source
            .get(..byte)
            .and_then(|prefix| prefix.rfind('\n'))
            .map_or(0, |newline| newline + 1);
        self.source
            .get(line_start..)
            .map_or(0, |line| line.len() - line.trim_start_matches(' ').len())
    }

    #[expect(
        clippy::too_many_lines,
        reason = "keeping this semantic operation together makes its state transitions easier to audit"
    )]
    fn eval_node(&mut self, view: NodeView<'_>) -> Contributions {
        let mut out = Contributions::default();
        match view.node {
            Node::Mapping(entry) => {
                let previous_site = self.enter_hole_site(entry.key.span);
                let key = self.entry_key(&entry.key);
                self.push_key_reads(&key);
                self.restore_site(previous_site);
                let mut value = Guarded::empty();
                if let Some(block) = &entry.block {
                    value.extend(self.eval_block_scalar(block));
                }
                if let Some(parts) = &entry.value {
                    let evaluated = self.eval_scalar_parts(parts);
                    // A sourced value hole that lowered to nothing still
                    // occupies the value position: without an arm the entry
                    // would read as an OPEN header and adopt a following
                    // floated splice as its own value.
                    if evaluated.is_empty() {
                        value.extend(Guarded::unconditional(AbstractFragment::Opaque(
                            Opaque::default(),
                        )));
                    } else {
                        value.extend(evaluated);
                    }
                }
                let (children, siblings) = self.split_structural_children(view, entry.indent);
                if !children.is_empty() {
                    let mut child = self.eval_node_list(&children);
                    let opened_empty = entry.value.is_none() && entry.block.is_none();
                    let marked_at = content_child_mark(&entry.children, entry.indent);
                    value.extend(child.take_floating_below(entry.indent, opened_empty, marked_at));
                    out.floating.append(&mut child.floating);
                    out.loop_control.extend(child.take_loop_control());
                    value.extend(child.assemble());
                }
                // A bare output hanging at or above a block-scalar entry's
                // indent (`key: |` followed by a column-0 `{{- include … }}`)
                // renders into the still-open block whenever its text is
                // deeper than the entry, so it contributes block text — not
                // structure escaping to the parent container.
                let siblings = if entry.block.is_some() {
                    let (adopted, rest): (Vec<_>, Vec<_>) = siblings
                        .into_iter()
                        .partition(|child| matches!(child.node, Node::Output(_)));
                    for adopted_view in adopted {
                        if let Node::Output(action) = adopted_view.node {
                            value.extend(self.eval_block_adopted_output(action.span));
                        }
                    }
                    rest
                } else {
                    siblings
                };
                out.merge_entry(key, value);
                if !siblings.is_empty() {
                    out.extend(self.eval_node_list(&siblings));
                }
            }
            Node::Sequence(item) => {
                let mut value = Guarded::empty();
                if let Some(block) = &item.block {
                    value.extend(self.eval_block_scalar(block));
                }
                if let Some(parts) = &item.value {
                    value.extend(self.eval_scalar_parts(parts));
                }
                let (children, siblings) = self.split_structural_children(view, item.indent);
                if !children.is_empty() {
                    let mut child = self.eval_node_list(&children);
                    // Items never accept same-indent output (the open-slot
                    // query pushes item frames without that allowance).
                    value.extend(child.take_floating_below(item.indent, false, None));
                    out.floating.append(&mut child.floating);
                    out.loop_control.extend(child.take_loop_control());
                    value.extend(child.assemble());
                }
                // `- |` items adopt shallow bare outputs as block text, the
                // same as block-scalar mapping entries above.
                let siblings = if item.block.is_some() {
                    let (adopted, rest): (Vec<_>, Vec<_>) = siblings
                        .into_iter()
                        .partition(|child| matches!(child.node, Node::Output(_)));
                    for adopted_view in adopted {
                        if let Node::Output(action) = adopted_view.node {
                            value.extend(self.eval_block_adopted_output(action.span));
                        }
                    }
                    rest
                } else {
                    siblings
                };
                out.items.push(value);
                if !siblings.is_empty() {
                    out.extend(self.eval_node_list(&siblings));
                }
            }
            Node::Scalar(line) => {
                if line
                    .content
                    .parts
                    .iter()
                    .any(|part| matches!(part, ScalarPart::Hole(_)))
                {
                    let value = self.eval_scalar_parts(&line.content);
                    out.values.extend(value);
                }
            }
            Node::Opaque(opaque) if opaque.kind == OpaqueKind::Assignment => {
                self.eval_assignment_span(opaque.span);
            }
            Node::Opaque(opaque) if opaque.kind == OpaqueKind::Break => {
                out.loop_control.breaks.push(Predicate::True);
            }
            Node::Opaque(opaque) if opaque.kind == OpaqueKind::Continue => {
                out.loop_control.continues.push(Predicate::True);
            }
            Node::Control(_) | Node::Output(_) | Node::Comment(_) | Node::Opaque(_) => {}
        }
        out
    }

    /// Split a container's in-scope children into real children and nodes
    /// the layout recovery hung under the container: YAML containers hold
    /// strictly deeper content — except sequence items, which may sit at
    /// their parent key's own indent — so anything else at or above the
    /// container indent evaluates as a sibling at the container's level (the
    /// line model's pop-by-indent rule). Explicitly-indented outputs float;
    /// the float rules own their placement.
    fn split_structural_children<'n>(
        &self,
        view: NodeView<'n>,
        container_indent: usize,
    ) -> (Vec<NodeView<'n>>, Vec<NodeView<'n>>) {
        view.in_scope_children()
            .into_iter()
            .partition(|child| self.node_belongs_inside(child.node, container_indent))
    }

    fn node_belongs_inside(&self, node: &Node, container_indent: usize) -> bool {
        match node {
            Node::Mapping(entry) => entry.indent > container_indent,
            Node::Sequence(item) => item.indent >= container_indent,
            Node::Scalar(line) => line.indent > container_indent,
            Node::Control(region) => region
                .branches
                .iter()
                .flat_map(|branch| &branch.body)
                .all(|child| self.node_belongs_inside(child, container_indent)),
            Node::Output(action) => {
                // Deeper lines always belong; the explicit-width probe (a
                // re-parse) only runs for the rare same-or-shallower case.
                self.line_indent(action.span.start) > container_indent
                    || parse_expr_text(self.text(action.span))
                        .iter()
                        .rev()
                        .any(|expr| expr.fragment_indent_width().is_some())
            }
            Node::Comment(_) | Node::Opaque(_) => true,
        }
    }

    pub(super) fn entry_key(&mut self, parts: &ScalarParts) -> EntryKey {
        let has_hole = parts
            .parts
            .iter()
            .any(|part| matches!(part, ScalarPart::Hole(_)));
        if !has_hole {
            let key = syntax::unquote_yaml_scalar(self.text(parts.span).trim()).to_string();
            if !key.is_empty() {
                return EntryKey::Literal(key);
            }
        }
        let mut string = AbstractString::default();
        for part in &parts.parts {
            match part {
                ScalarPart::Text(span) => {
                    let text = self.text(*span);
                    if !text.is_empty() {
                        string
                            .parts
                            .push(StringPart::Text([text.to_string()].into_iter().collect()));
                    }
                }
                ScalarPart::Hole(span) => {
                    let hole = self.hole_string(*span);
                    string.parts.extend(hole.parts);
                }
            }
        }
        EntryKey::Dynamic(string)
    }

    /// Evaluate a hole into flattened string parts (conditions from
    /// alternatives are dropped; used for keys, where alternatives project
    /// pathlessly anyway).
    fn hole_string(&mut self, span: Span) -> AbstractString {
        let arms = self.eval_hole_parts(span);
        AbstractString {
            parts: arms.into_iter().flat_map(|(_, parts)| parts).collect(),
            suppressed: false,
        }
    }
}