agent-first-data 0.41.0

Self-describing data and structured CLI contracts for AI agents — field-name suffixes for units and secrets, the afdata CLI for rendering, validation, path guards, and reading or editing structured documents (JSON, TOML, YAML, dotenv, INI, Markdown), plus libraries for Rust, Go, Python, TypeScript, and Bash.
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
//! YAML format backend. Reads via the noyalib `Value` view; mutates via the
//! lossless `cst::Document` editor so comments, ordering, styles, and untouched
//! source bytes are preserved.

use crate::document::{Addressing, DocumentError, DocumentResult, Value};
use noyalib::{
    DuplicateKeyPolicy, Mapping as YamlMapping, ParserConfig, Value as YamlValue,
    cst::{GreenChild, GreenNode, SyntaxKind, parse_document},
    from_str_with_config, to_string,
};

pub fn load(content: &str) -> DocumentResult<Value> {
    let (protected, literals) = protect_exact_numbers(content)?;
    let parser_config = ParserConfig::new()
        .duplicate_key_policy(DuplicateKeyPolicy::Error)
        .lossless_u64_integers(true);
    from_str_with_config::<YamlValue>(&protected, &parser_config)
        .map(|value| value_to_our_value(value, &literals))
        .map_err(|e| DocumentError::ParseError {
            format: "YAML".to_string(),
            detail: e.to_string(),
        })
}

/// Replace one value in a YAML source document while retaining all unrelated
/// source bytes. The document layer resolves keyed-list routes to indices before
/// editing. Escaped keys still lack a lossless CST path adapter.
///
/// Scalars go through the CST's own `set_value`, which matches the site's
/// quoting. Collections cannot: noyalib's `set_value` refuses to grow a scalar
/// site into a sequence or mapping under any circumstances, so a collection is
/// emitted as a block fragment and spliced over the value's span — see
/// `replace_collection_in_place`, which also documents what that costs.
pub(crate) fn set_preserving(content: &str, path: &str, value: &Value) -> DocumentResult<String> {
    let segments = crate::document::parse_path(path)?;
    if is_blank_document(content) {
        return set_in_blank_document(content, &segments, value);
    }
    if let Some((last, parents)) = segments.split_last()
        && last == "-"
        && array_at_path(&load(content)?, &crate::document::join_path(parents), "set").is_ok()
    {
        guard_cst_segments(content, parents, "set", false)?;
        return append_array_item_preserving(content, &crate::document::join_path(parents), value)
            .map_err(|error| match error {
                DocumentError::UnsupportedOperation { format, detail, .. } => {
                    DocumentError::UnsupportedOperation {
                        format,
                        operation: "set".into(),
                        detail,
                    }
                }
                other => other,
            });
    }
    let yaml_path = cst_path(&segments, "set")?;
    guard_cst_segments(content, &segments, "set", true)?;
    let mut document = parse_document(content).map_err(|error| DocumentError::ParseError {
        format: "YAML".to_string(),
        detail: error.to_string(),
    })?;
    // The leaf itself may be an alias site: a scalar written there replaces the
    // `*name` reference, which is the key the caller named.
    refuse_shared_nodes(
        &document,
        content,
        &segments,
        segments.len() - 1,
        "set",
        true,
    )?;
    // Existing leaf: replace in place (preserves the scalar's style). Missing
    // leaf under an existing mapping: splice a sibling entry via `insert_entry`.
    let mut expected = load(content)?;
    // A key the mapping only inherits through a `<<` merge reads as present but
    // has no entry in the source: writing it adds one, which overrides the merge.
    let exists = crate::document::get_path_ref(&expected, path, Addressing::INDEX_ONLY).is_ok()
        && segments.last().is_some_and(|last| {
            last.parse::<usize>().is_ok() || document.key_span(&yaml_path).is_some()
        });
    // Float and small unsigned inputs canonicalize to the reader's numeric
    // variants. Compare that representation while retaining exact literals.
    let canonical = load(&save(value)?)?;
    crate::document::set_path(&mut expected, path, &canonical, Addressing::INDEX_ONLY)?;
    if exists && matches!(value, Value::Array(_) | Value::Object(_)) {
        replace_collection_in_place(&mut document, content, &segments, &yaml_path, value)?;
    } else if exists {
        let result = if let Value::Number(text) = value {
            document.set(&yaml_path, text)
        } else if let Value::String(text) = value
            && yaml_needs_legacy_quotes(text)
        {
            document.set(&yaml_path, &quoted_yaml_string(text))
        } else {
            document.set_value(&yaml_path, &to_noyalib_value(value)?)
        };
        result.map_err(|error| edit_refused("set", &error))?;
    } else {
        // Grow missing mapping parents from the deepest existing ancestor.
        let original = load(content)?;
        for index in 0..segments.len().saturating_sub(1) {
            let prefix = crate::document::join_path(&segments[..=index]);
            if crate::document::get_path(&original, &prefix, Addressing::INDEX_ONLY).is_err() {
                let parent = cst_path(&segments[..index], "set")?;
                // An empty flow mapping has nothing to lay out around, so it
                // grows like a block one — however much space is inside `{ }`.
                if document.span_at(&parent).is_some_and(|(start, end)| {
                    let text = content[start..end].trim();
                    let empty = text
                        .strip_circumfix('{', '}')
                        .is_some_and(|inner| inner.trim().is_empty());
                    text.starts_with('{') && !empty
                }) {
                    return Err(DocumentError::UnsupportedOperation {
                        format: "YAML".into(),
                        operation: "set".into(),
                        detail: "creating parents inside a flow mapping is not supported".into(),
                    });
                }
                let mut nested = value.clone();
                for key in segments[index + 1..].iter().rev() {
                    nested = Value::Object([(key.clone(), nested)].into_iter().collect());
                }
                return set_preserving(content, &prefix, &nested);
            }
        }
        let (last, parents) = segments.split_last().ok_or(DocumentError::EmptyPath)?;
        if last.parse::<usize>().is_ok() {
            return Err(DocumentError::UnsupportedOperation {
                format: "YAML".to_string(),
                operation: "set".to_string(),
                detail: "cannot create a new sequence index; the element must already exist"
                    .to_string(),
            });
        }
        let parent_path = if parents.is_empty() {
            String::new()
        } else {
            cst_path(parents, "set")?
        };
        let result = match value {
            // An empty collection through the typed path lands on its own line
            // (`tags:` then `  []`); the fragment spelling keeps it inline,
            // which is how anyone writes it by hand.
            Value::Array(items) if items.is_empty() => {
                document.insert_entry(&parent_path, last, "[]")
            }
            Value::Object(entries) if entries.is_empty() => {
                document.insert_entry(&parent_path, last, "{}")
            }
            // A new key is the one place noyalib will emit a collection itself,
            // indenting it under the key and rolling back if the re-parse
            // disagrees. Preferred over a hand-built fragment for exactly that.
            Value::Array(_) | Value::Object(_) => {
                document.insert_entry_value(&parent_path, last, &to_noyalib_value(value)?)
            }
            _ => document.insert_entry(&parent_path, last, yaml_fragment(value, "set")?.trim_end()),
        };
        if result.is_err() {
            // The fragment tier requires a block anchor; typed insertion also
            // handles empty and flow mappings, including the key's quoting.
            // Exact numbers are inserted through a null site, then replaced
            // verbatim so their spelling never passes through f64.
            let retry = if let Value::Number(text) = value {
                document
                    .insert_entry_value(&parent_path, last, &YamlValue::Null)
                    .and_then(|()| document.set(&yaml_path, text))
            } else {
                document.insert_entry_value(&parent_path, last, &to_noyalib_value(value)?)
            };
            if let Err(error) = retry {
                // noyalib finds no anchor in a mapping whose only own entry is
                // a `<<` merge, nor in a sequence item's mapping that holds a
                // single key (`- name: web`, which is exactly what `add` leaves
                // behind); lay the entry out beside the merge key or under the
                // dash itself.
                // Upstream: https://github.com/sebastienrousseau/noyalib/issues/499
                if !insert_beside_merge_key(&mut document, content, &parent_path, last, value)?
                    && !append_to_sequence_item_mapping(
                        &mut document,
                        content,
                        &parent_path,
                        last,
                        value,
                    )?
                {
                    return Err(edit_refused("set", &error));
                }
            }
        }
    }
    document
        .validate()
        .map_err(|error| DocumentError::ParseError {
            format: "YAML".to_string(),
            detail: error.to_string(),
        })?;
    let output = if exists {
        document.to_string()
    } else {
        quote_inserted_scalars(&document, &yaml_path)
    };
    if load(&output)? != expected {
        return Err(DocumentError::UnsupportedOperation {
            format: "YAML".to_string(),
            operation: "set".to_string(),
            detail: "YAML edit did not preserve the requested document value".to_string(),
        });
    }
    Ok(output)
}

/// True when `content` holds no YAML node at all: only blank lines, comments,
/// and at most an opening `---`. Such a document reads as null — a blank
/// frontmatter template, a fresh config file — and a `set` starts its mapping.
pub(crate) fn is_blank_document(content: &str) -> bool {
    let mut markers = 0;
    content.lines().all(|line| {
        let line = line.trim();
        if line == "---" {
            markers += 1;
            return markers == 1;
        }
        line.is_empty() || line.starts_with('#')
    })
}

/// Append the mapping `path = value` after whatever comments `content` has.
fn set_in_blank_document(
    content: &str,
    segments: &[String],
    value: &Value,
) -> DocumentResult<String> {
    if segments
        .iter()
        .any(|segment| segment == "-" || segment.parse::<usize>().is_ok())
    {
        return Err(DocumentError::UnsupportedOperation {
            format: "YAML".to_string(),
            operation: "set".to_string(),
            detail: "an empty document has no sequence to index into".to_string(),
        });
    }
    let mut nested = value.clone();
    for segment in segments.iter().rev() {
        nested = Value::Object([(segment.clone(), nested)].into_iter().collect());
    }
    let rendered = save(&nested)?;
    let body = rendered.trim_prefix("---\n");
    let newline = if content.contains("\r\n") {
        "\r\n"
    } else {
        "\n"
    };
    let mut output = content.to_string();
    if !output.is_empty() && !output.ends_with('\n') {
        output.push_str(newline);
    }
    for line in body.trim_end_matches('\n').split('\n') {
        output.push_str(line);
        output.push_str(newline);
    }
    if load(&output)? != load(&save(&nested)?)? {
        return Err(DocumentError::UnsupportedOperation {
            format: "YAML".to_string(),
            operation: "set".to_string(),
            detail: "YAML edit did not preserve the requested document value".to_string(),
        });
    }
    Ok(output)
}

/// Splice a block-style collection over the span of an existing value.
///
/// noyalib's typed `set_value` refuses a sequence or mapping outright, so the
/// only route is a fragment written over the value's byte span. Three details
/// make that safe rather than approximate:
///
/// * The start widens back over the whitespace between the `:` and the old
///   value, because a block collection has to begin on its own line — spliced
///   at the raw span start it would either sit at column 0 or leave the source's
///   own newline behind as a blank line.
/// * The end widens over a trailing `#` comment. The span the CST reports stops
///   before it, so leaving it would re-attach a comment written about the *old*
///   last element to whatever the new one happens to be. Silently moving a
///   comment onto a different value is worse than dropping it with the value it
///   described.
/// * A path reached through an alias is refused. `span_at` resolves through
///   aliases to the anchor, so editing `other: *b` would rewrite `base: &b`
///   instead — a different key than the caller named.
///
/// The cost, which has no workaround in this version: comments and blank lines
/// *inside* the replaced collection are dropped, because no API models them as
/// movable. Everything outside the span — surrounding keys, their comments,
/// key order, quote styles, the trailing newline — is preserved byte for byte.
fn replace_collection_in_place(
    document: &mut noyalib::cst::Document,
    content: &str,
    segments: &[String],
    yaml_path: &str,
    value: &Value,
) -> DocumentResult<()> {
    let unsupported = |detail: String| DocumentError::UnsupportedOperation {
        format: "YAML".to_string(),
        operation: "set".to_string(),
        detail,
    };
    let (value_start, value_end) = document
        .span_at(yaml_path)
        .ok_or_else(|| unsupported(format!("could not locate the value at `{yaml_path}`")))?;
    let newline = if content.contains("\r\n") {
        "\r\n"
    } else {
        "\n"
    };
    let Some((key_start, key_end)) = document.key_span(yaml_path) else {
        // A sequence element has no key: the collection starts on the dash's
        // own line and continues two columns in from it.
        let dash_column = preceding_sequence_dash_column(content, value_start).ok_or_else(|| {
            unsupported(format!(
                "a collection can replace only a block sequence element, and `{yaml_path}` is not one"
            ))
        })?;
        let indent = dash_column + 2;
        let fragment = block_fragment(value, document.indent_unit(), indent, newline)?;
        let inline = fragment
            .strip_prefix(newline)
            .and_then(|rest| rest.strip_prefix(" ".repeat(indent).as_str()))
            .unwrap_or_else(|| fragment.trim_start());
        let end = end_of_trailing_inline_comment(content, value_end);
        return document
            .replace_span(value_start, end, inline)
            .map_err(|error| edit_refused("set", &error));
    };
    if value_start < key_end {
        return Err(through_alias_refused(
            segments,
            segments,
            anchor_before(document, value_start).as_deref(),
            "set",
        ));
    }

    let bytes = content.as_bytes();
    let key_column = line_column_of(content, key_start);
    let indent = key_column + document.indent_unit();

    let mut start = value_start;
    while start > 0 && matches!(bytes[start - 1], b' ' | b'\t' | b'\n' | b'\r') {
        start -= 1;
    }
    let end = end_of_trailing_inline_comment(content, value_end);

    let fragment = block_fragment(value, document.indent_unit(), indent, newline)?;
    document
        .replace_span(start, end, &fragment)
        .map_err(|error| edit_refused("set", &error))
}

/// Append `key: value` to the block mapping at `parent_path` when that mapping
/// is a sequence element. Returns `false` when it is not one, leaving the
/// caller's own error to report.
fn append_to_sequence_item_mapping(
    document: &mut noyalib::cst::Document,
    content: &str,
    parent_path: &str,
    key: &str,
    value: &Value,
) -> DocumentResult<bool> {
    let Some((start, end)) = document.span_at(parent_path) else {
        return Ok(false);
    };
    let Some(dash_column) = preceding_sequence_dash_column(content, start) else {
        return Ok(false);
    };
    if content[start..end].trim_start().starts_with('{') {
        return Ok(false);
    }
    let newline = if content.contains("\r\n") {
        "\r\n"
    } else {
        "\n"
    };
    let entry = Value::Object([(key.to_string(), value.clone())].into_iter().collect());
    let fragment = block_fragment(&entry, document.indent_unit(), dash_column + 2, newline)?;
    let at = end_of_trailing_inline_comment(content, end);
    document
        .replace_span(at, at, &fragment)
        .map_err(|error| edit_refused("set", &error))?;
    Ok(true)
}

/// Add `key: value` as an own entry of the block mapping at `parent_path`,
/// laid out on the line after its `<<` merge key. Returns `false` when the
/// mapping has no such key or its layout is not one this can place an entry in,
/// leaving the caller's own error to report.
///
/// An own entry wins over a merged one, so this is also how a merged key is
/// overridden.
fn insert_beside_merge_key(
    document: &mut noyalib::cst::Document,
    content: &str,
    parent_path: &str,
    key: &str,
    value: &Value,
) -> DocumentResult<bool> {
    // The CST has no key span for `<<`, but a mapping whose only own entry is the
    // merge begins with it.
    // The span of a block mapping includes its first line's indentation.
    let Some(key_start) = document.span_at(parent_path).and_then(|(start, end)| {
        let text = &content[start..end];
        let key_start = start + (text.len() - text.trim_start_matches(' ').len());
        content[key_start..].starts_with("<<").then_some(key_start)
    }) else {
        return Ok(false);
    };
    let line_start = content[..key_start]
        .rfind('\n')
        .map_or(0, |index| index + 1);
    if !content[line_start..key_start]
        .bytes()
        .all(|byte| byte == b' ')
    {
        return Ok(false);
    }
    let column = key_start - line_start;
    let mut at = content[key_start..]
        .find('\n')
        .map_or(content.len(), |offset| key_start + offset);
    // A merge value spread over several lines would put the new entry inside it.
    let next_line = content[at..].trim_start_matches(['\r', '\n']);
    let continues = next_line.lines().next().is_some_and(|line| {
        !line.trim().is_empty() && line.len() - line.trim_start().len() > column
    });
    if continues {
        return Ok(false);
    }
    if at > key_start && content.as_bytes()[at - 1] == b'\r' {
        at -= 1;
    }
    let newline = if content.contains("\r\n") {
        "\r\n"
    } else {
        "\n"
    };
    let entry = Value::Object([(key.to_string(), value.clone())].into_iter().collect());
    let fragment = block_fragment(&entry, document.indent_unit(), column, newline)?;
    document
        .replace_span(at, at, &fragment)
        .map_err(|error| edit_refused("set", &error))?;
    Ok(true)
}

/// Render `value` as the bytes that go after a mapping key.
///
/// An empty collection stays inline (` []`), because a bare `key:` parses as
/// null rather than as an empty sequence — the space is load-bearing. Anything
/// else becomes a block, preceded by a newline and indented under its key.
fn block_fragment(
    value: &Value,
    indent_unit: usize,
    indent: usize,
    newline: &str,
) -> DocumentResult<String> {
    match value {
        Value::Array(items) if items.is_empty() => return Ok(" []".to_string()),
        Value::Object(entries) if entries.is_empty() => return Ok(" {}".to_string()),
        _ => {}
    }
    let config = noyalib::SerializerConfig::new()
        .indent(indent_unit)
        .flow_style(noyalib::FlowStyle::Block);
    // Emitted by noyalib rather than by hand: element quoting has to survive
    // values like `true`, `123`, `a: b` and `#c`, which are only scalars
    // because they are quoted.
    let rendered = render(value, Some(&config))?;
    let pad = " ".repeat(indent);
    let mut fragment = String::new();
    for line in rendered.trim_end_matches(['\r', '\n']).lines() {
        fragment.push_str(newline);
        if line.is_empty() {
            continue;
        }
        fragment.push_str(&pad);
        fragment.push_str(line);
    }
    Ok(fragment)
}

/// Column of `offset` within its line, counting bytes from the line start.
fn line_column_of(content: &str, offset: usize) -> usize {
    let line_start = content[..offset].rfind('\n').map_or(0, |index| index + 1);
    offset - line_start
}

/// End of the `#` comment trailing the value that ends at `value_end`, or
/// `value_end` when the rest of the line holds anything else.
fn end_of_trailing_inline_comment(content: &str, value_end: usize) -> usize {
    let bytes = content.as_bytes();
    let mut index = value_end;
    while index < bytes.len() && matches!(bytes[index], b' ' | b'\t') {
        index += 1;
    }
    if index >= bytes.len() || bytes[index] != b'#' {
        return value_end;
    }
    while index < bytes.len() && bytes[index] != b'\n' {
        index += 1;
    }
    if index > 0 && bytes[index - 1] == b'\r' {
        index -= 1;
    }
    index
}

/// Remove an existing YAML entry through the lossless CST editor.
pub(crate) fn unset_preserving(content: &str, path: &str) -> DocumentResult<String> {
    let segments = crate::document::parse_path(path)?;
    let (leaf, parents) = segments.split_last().ok_or(DocumentError::EmptyPath)?;
    let parent_path = crate::document::join_path(parents);
    let root = load(content)?;
    let parent = if parents.is_empty() {
        &root
    } else {
        crate::document::get_path_ref(&root, &parent_path, Addressing::INDEX_ONLY)?
    };
    if let (Value::Array(_), Ok(index)) = (parent, leaf.parse::<usize>()) {
        return remove_array_item(content, &parent_path, index, "unset");
    }
    let yaml_path = cst_path(&segments, "unset")?;
    guard_cst_segments(content, &segments, "unset", false)?;
    let mut document = parse_document(content).map_err(|error| DocumentError::ParseError {
        format: "YAML".to_string(),
        detail: error.to_string(),
    })?;
    refuse_shared_nodes(
        &document,
        content,
        &segments,
        segments.len() - 1,
        "unset",
        false,
    )?;
    document
        .remove(&yaml_path)
        .map_err(|error| edit_refused("unset", &error))?;
    document
        .validate()
        .map_err(|error| DocumentError::ParseError {
            format: "YAML".to_string(),
            detail: error.to_string(),
        })?;
    Ok(document.to_string())
}

/// Append an item to an existing block YAML sequence using the CST's
/// indentation-aware editor.
pub(crate) fn append_array_item_preserving(
    content: &str,
    path: &str,
    item: &Value,
) -> DocumentResult<String> {
    let segments = array_path_segments(path)?;
    let yaml_path = cst_path(&segments, "add")?;
    let mut document = parse_document(content).map_err(|error| DocumentError::ParseError {
        format: "YAML".to_string(),
        detail: error.to_string(),
    })?;
    refuse_shared_nodes(&document, content, &segments, segments.len(), "add", false)?;
    let loaded = load(content)?;
    let existing = array_at_path(&loaded, path, "add")?;
    let previous_len = existing.len();
    // Validate before the empty-sequence shortcut too: JSON would otherwise
    // silently serialize a non-finite float as null.
    let canonical_item = load(&save(item)?)?;
    if previous_len == 0 {
        // The CST's `push_back` needs an existing item to take indentation
        // from, so it refuses on `tags: []`. Writing the whole one-element
        // sequence gets there instead, and costs nothing: an empty collection
        // has no interior comments or layout to preserve.
        // A sequence element has a value span but no mapping-key span, so the
        // mapping-oriented collection writer cannot grow an empty nested array.
        // A one-line flow sequence fills the empty span without touching its
        // dash or surrounding comments, just as it does for a root empty
        // sequence. It comes from the YAML emitter, not a JSON one: JSON leaves
        // DEL and C1 controls raw, which YAML forbids in source.
        if path.is_empty()
            || segments
                .last()
                .is_some_and(|part| part.parse::<usize>().is_ok())
        {
            let (start, end) = document
                .span_at(&yaml_path)
                .ok_or_else(|| DocumentError::PathNotFound { path: path.into() })?;
            let replacement = flow_fragment(&Value::Array(vec![item.clone()]))?;
            document
                .replace_span(start, end, &replacement)
                .map_err(|error| edit_refused("add", &error))?;
            let output = document.to_string();
            let edited = load(&output)?;
            if array_at_path(&edited, path, "add")?.as_slice()
                != std::slice::from_ref(&canonical_item)
            {
                return Err(DocumentError::UnsupportedOperation {
                    format: "YAML".into(),
                    operation: "add".into(),
                    detail: "the source edit did not reproduce the requested item".into(),
                });
            }
            return Ok(output);
        }
        return set_preserving(content, path, &Value::Array(vec![item.clone()]));
    }
    let mut fragment = yaml_fragment(item, "add")?;
    {
        let item_path = format!("{yaml_path}[{}]", previous_len - 1);
        let (item_start, _) =
            document
                .span_at(&item_path)
                .ok_or_else(|| DocumentError::UnsupportedOperation {
                    format: "YAML".to_string(),
                    operation: "add".to_string(),
                    detail: "could not resolve the existing sequence-item indentation".to_string(),
                })?;
        let dash_column = preceding_sequence_dash_column(content, item_start).ok_or_else(|| {
            DocumentError::UnsupportedOperation {
                format: "YAML".to_string(),
                operation: "add".to_string(),
                detail: "only block sequences can be extended without rebuilding the document"
                    .to_string(),
            }
        })?;
        fragment = indent_continuation_lines(fragment.trim_end(), dash_column + 2);
    }
    document
        .push_back(&yaml_path, fragment.trim_end())
        .map_err(|error| edit_refused("add", &error))?;
    document
        .validate()
        .map_err(|error| DocumentError::ParseError {
            format: "YAML".to_string(),
            detail: error.to_string(),
        })?;
    let output = document.to_string();
    let edited = load(&output)?;
    let edited_items = array_at_path(&edited, path, "add")?;
    if edited_items.len() != previous_len + 1 || edited_items.last() != Some(&canonical_item) {
        return Err(DocumentError::UnsupportedOperation {
            format: "YAML".to_string(),
            operation: "add".to_string(),
            detail: "the source edit did not reproduce the requested keyed item".to_string(),
        });
    }
    Ok(output)
}

/// Remove one item from a YAML sequence by numeric index.
pub(crate) fn remove_array_item_preserving(
    content: &str,
    path: &str,
    index: usize,
) -> DocumentResult<String> {
    remove_array_item(content, path, index, "remove")
}

fn remove_array_item(
    content: &str,
    path: &str,
    index: usize,
    operation: &str,
) -> DocumentResult<String> {
    let segments = array_path_segments(path)?;
    let mut item_segments = segments.clone();
    item_segments.push(index.to_string());
    guard_cst_segments(content, &item_segments, operation, false)?;
    let loaded = load(content)?;
    let len = array_at_path(&loaded, path, operation)?.len();
    let mut document = parse_document(content).map_err(|error| DocumentError::ParseError {
        format: "YAML".to_string(),
        detail: error.to_string(),
    })?;
    refuse_shared_nodes(
        &document,
        content,
        &item_segments,
        segments.len(),
        operation,
        false,
    )?;
    let yaml_path = cst_path(&segments, operation)?;
    if len == 1 && index == 0 {
        if !path.is_empty()
            && segments
                .last()
                .is_some_and(|part| part.parse::<usize>().is_err())
        {
            return set_preserving(content, path, &Value::Array(Vec::new()));
        }
        let (start, end) = if path.is_empty() {
            root_value_span(document.syntax(), 0)
        } else {
            document.span_at(&yaml_path)
        }
        .ok_or_else(|| DocumentError::PathNotFound { path: path.into() })?;
        let end = start + content[start..end].trim_end().len();
        let prefix = &content[..start];
        let before_space = prefix.trim_end_matches([' ', '\t', '\r', '\n']);
        let (start, replacement) = if !path.is_empty()
            && prefix[before_space.len()..].contains('\n')
            && before_space.ends_with('-')
        {
            // A block sequence may start on the line after its parent's dash.
            // Keep the replacement flow sequence on the parent item's line.
            (before_space.len(), " []")
        } else {
            (start, "[]")
        };
        document
            .replace_span(start, end, replacement)
            .map_err(|error| edit_refused(operation, &error))?;
        let output = document.to_string();
        if array_at_path(&load(&output)?, path, operation)?.is_empty() {
            return Ok(output);
        }
        return Err(DocumentError::WriteWouldCorrupt {
            format: "YAML".into(),
            detail: "edited source did not reproduce an empty sequence".into(),
        });
    }
    document
        .remove(&format!("{yaml_path}[{index}]"))
        .map_err(|error| edit_refused(operation, &error))?;
    document
        .validate()
        .map_err(|error| DocumentError::ParseError {
            format: "YAML".to_string(),
            detail: error.to_string(),
        })?;
    Ok(document.to_string())
}

// The root sequence span can include comments and document framing. Its
// significant CST tokens delimit the value while leaving that trivia in place.
fn root_value_span(node: &GreenNode, mut offset: usize) -> Option<(usize, usize)> {
    let mut span: Option<(usize, usize)> = None;
    for child in node.children() {
        let end = offset + child.text_len();
        let child_span = match child {
            GreenChild::Node(inner) => root_value_span(inner, offset),
            GreenChild::Token {
                kind:
                    SyntaxKind::Whitespace
                    | SyntaxKind::Newline
                    | SyntaxKind::Comment
                    | SyntaxKind::Bom
                    | SyntaxKind::Directive
                    | SyntaxKind::DocStart
                    | SyntaxKind::DocEnd,
                ..
            } => None,
            GreenChild::Token { .. } => Some((offset, end)),
        };
        if let Some((first, last)) = child_span {
            span = Some((span.map_or(first, |(start, _)| start), last));
        }
        offset = end;
    }
    span
}

/// An empty keyed-list prefix names a root sequence. Ordinary set/unset paths
/// still pass through `parse_path` directly and therefore remain non-empty.
fn array_path_segments(path: &str) -> DocumentResult<Vec<String>> {
    if path.is_empty() {
        Ok(Vec::new())
    } else {
        crate::document::parse_path(path)
    }
}

fn array_at_path<'a>(
    value: &'a Value,
    path: &str,
    operation: &str,
) -> DocumentResult<&'a Vec<Value>> {
    let target = if path.is_empty() {
        value
    } else {
        crate::document::get_path_ref(value, path, Addressing::INDEX_ONLY)?
    };
    target
        .as_array()
        .ok_or_else(|| DocumentError::UnsupportedOperation {
            format: "YAML".to_string(),
            operation: operation.to_string(),
            detail: "target is not an array".to_string(),
        })
}

fn preceding_sequence_dash_column(content: &str, value_start: usize) -> Option<usize> {
    let bytes = content.as_bytes();
    let mut position = value_start;
    let dash = loop {
        position = position.checked_sub(1)?;
        match bytes.get(position)? {
            b' ' | b'\t' => {}
            b'-' => break position,
            _ => return None,
        }
    };
    let line_start = content.as_bytes()[..dash]
        .iter()
        .rposition(|byte| *byte == b'\n')
        .map_or(0, |newline| newline + 1);
    Some(dash - line_start)
}

fn indent_continuation_lines(fragment: &str, indent: usize) -> String {
    if !fragment.contains('\n') {
        return fragment.to_string();
    }
    let padding = " ".repeat(indent);
    let mut output = String::with_capacity(fragment.len() + indent * 4);
    for (index, line) in fragment.split('\n').enumerate() {
        if index > 0 {
            output.push('\n');
            if !line.is_empty() {
                output.push_str(&padding);
            }
        }
        output.push_str(line);
    }
    output
}

fn cst_path(segments: &[String], operation: &str) -> DocumentResult<String> {
    let mut path = String::new();
    for segment in segments {
        if segment.contains(['.', '\\', '[', ']']) {
            return Err(DocumentError::UnsupportedOperation {
                format: "YAML".to_string(),
                operation: operation.to_string(),
                detail:
                    "escaped or bracketed YAML keys require a quoted-key CST span and are not supported"
                        .to_string(),
            });
        }
        if let Ok(index) = segment.parse::<usize>() {
            path.push_str(&format!("[{index}]"));
        } else {
            if !path.is_empty() {
                path.push('.');
            }
            path.push_str(segment);
        }
    }
    Ok(path)
}

/// The editor's own reason an in-place edit was refused, with the name of the
/// internal routine that raised it and its own advice dropped. Merge keys need
/// no advice here: the edits a `<<` merge affects are recognized structurally
/// before the editor is asked.
fn edit_refused(operation: &str, error: &noyalib::Error) -> DocumentError {
    let reason = match error {
        noyalib::Error::Parse(message) | noyalib::Error::ParseWithLocation { message, .. } => {
            message.clone()
        }
        other => other.to_string(),
    };
    let reason = match reason.split_once(": ") {
        Some((routine, rest))
            if !routine.is_empty()
                && routine.bytes().all(|b| b.is_ascii_lowercase() || b == b'_') =>
        {
            rest.to_string()
        }
        _ => reason,
    };
    // Past the first em dash the editor advises in terms of its own verbs,
    // which are not this command's; keep the diagnosis only.
    let diagnosis = reason.split(" \u{2014} ").next().unwrap_or(&reason);
    let detail = format!("cannot safely edit this YAML layout in place: {diagnosis}");
    DocumentError::UnsupportedOperation {
        format: "YAML".to_string(),
        operation: operation.to_string(),
        detail,
    }
}

/// The refusal for an edit whose target is reached through `*alias`.
///
/// Every CST write resolves an alias to its anchor's bytes, so the edit would
/// land in `&alias` and show up at every alias of it — a different key than
/// the caller named. One message for every verb that meets one.
fn through_alias_refused(
    target: &[String],
    site: &[String],
    alias: Option<&str>,
    operation: &str,
) -> DocumentError {
    let alias = alias.map_or_else(|| "a YAML alias".to_string(), |name| format!("`*{name}`"));
    let target = crate::document::join_path(target);
    let site = crate::document::join_path(site);
    let location = if site == target {
        String::new()
    } else {
        format!(" at `{site}`")
    };
    DocumentError::SharedNode {
        operation: operation.to_string(),
        path: target,
        detail: format!(
            "it is reached through the alias {alias}{location}, so the edit would land in the \
             anchored value and change every alias of it; write the alias site itself to give \
             it a value of its own"
        ),
    }
}

/// The refusal for an edit inside a value that `*alias` sites share: the write
/// would show up at every one of them, which is more keys than the one named.
fn shared_by_aliases_refused(
    target: &[String],
    anchored: &[String],
    anchor: &str,
    sites: usize,
    operation: &str,
) -> DocumentError {
    let anchored = crate::document::join_path(anchored);
    DocumentError::SharedNode {
        operation: operation.to_string(),
        path: crate::document::join_path(target),
        detail: format!(
            "`{anchored}` is anchored as `&{anchor}` and aliased at {sites} other site(s), so \
             the edit would change every one of them; write each alias site to give it a value \
             of its own first"
        ),
    }
}

/// The refusal for an edit of a key that a `<<` merge supplies: the mapping has
/// no entry of its own to write or remove, only the one it inherits.
fn inherited_by_merge_refused(target: &[String], operation: &str) -> DocumentError {
    DocumentError::SharedNode {
        operation: operation.to_string(),
        path: crate::document::join_path(target),
        detail: "the mapping inherits this key through a `<<` merge and has no entry of its \
                 own to change in place; `set` it to give the mapping an entry that \
                 overrides the merge"
            .to_string(),
    }
}

/// The anchor whose value begins at `value_start`: the closest one declared
/// before it, since an anchor mark sits directly in front of its value.
fn anchor_before(document: &noyalib::cst::Document, value_start: usize) -> Option<String> {
    document
        .anchors()
        .into_iter()
        .rev()
        .find(|anchor| anchor.mark_span.1 <= value_start)
        .map(|anchor| anchor.name)
}

/// Refuse an edit whose route runs through nodes it would change beyond the
/// key named. Three shapes, all of them bytes shared with another site:
///
/// * a node reached through an alias (`ref.k` where `ref: *b`), among the first
///   `walked` ones. A writer that replaces the node at `target` itself passes
///   one less than its length, since an alias site written over is the key the
///   caller named;
/// * a node anchored with live aliases (`base` in `base: &b`, `ref: *b`), at any
///   depth including the target: its text is every alias's text;
/// * a key the mapping only inherits through a `<<` merge, which has no entry of
///   its own to write or remove.
///
/// `span_at` resolves an alias to its anchor's value, which always sits
/// earlier in the source than the alias site. So a node is reached through an
/// alias exactly when its value starts before something that must precede it:
/// its own key, the end of the previous sequence element, or its parent's
/// start. The value view cannot tell; only positions can.
fn refuse_shared_nodes(
    document: &noyalib::cst::Document,
    content: &str,
    target: &[String],
    walked: usize,
    operation: &str,
    leaf_may_be_inherited: bool,
) -> DocumentResult<()> {
    let loaded = load(content)?;
    let mut current = Some(&loaded);
    for (index, segment) in target.iter().enumerate() {
        let prefix = &target[..=index];
        let yaml_prefix = cst_path(prefix, operation)?;
        current = match current {
            Some(Value::Object(object)) => object.get(segment),
            Some(Value::Array(items)) => segment
                .parse::<usize>()
                .ok()
                .and_then(|position| items.get(position)),
            _ => None,
        };
        let Some((start, _)) = document.span_at(&yaml_prefix) else {
            // A value the reader sees but the source holds no entry for: the
            // mapping inherits it through a merge. Otherwise it is missing, or
            // an implicit null, and nothing below it can be reached.
            if current.is_some()
                && segment.parse::<usize>().is_err()
                && document.key_span(&yaml_prefix).is_none()
                && !(leaf_may_be_inherited && index + 1 == target.len())
            {
                return Err(inherited_by_merge_refused(prefix, operation));
            }
            return Ok(());
        };
        let through_alias = match segment.parse::<usize>() {
            Ok(0) if index > 0 => document
                .span_at(&cst_path(&target[..index], operation)?)
                .is_some_and(|(parent_start, _)| start < parent_start),
            Ok(0) => false,
            Ok(position) => {
                let previous = format!(
                    "{}[{}]",
                    cst_path(&target[..index], operation)?,
                    position - 1
                );
                document
                    .span_at(&previous)
                    .is_some_and(|(_, previous_end)| start < previous_end)
            }
            Err(_) => document
                .key_span(&yaml_prefix)
                .is_some_and(|(_, key_end)| start < key_end),
        };
        if through_alias {
            if index >= walked {
                // The alias site itself is being replaced, not the resolved subtree.
                return Ok(());
            }
            return Err(through_alias_refused(
                target,
                prefix,
                anchor_before(document, start).as_deref(),
                operation,
            ));
        }
        if let Some((anchor, sites)) = anchor_with_sites(document, content, start) {
            return Err(shared_by_aliases_refused(
                target, prefix, &anchor, sites, operation,
            ));
        }
    }
    if operation != "add"
        && let Some((start, end)) = document.span_at(&cst_path(target, operation)?)
    {
        for anchor in document.anchors() {
            if anchor.mark_span.0 < start || anchor.mark_span.1 > end {
                continue;
            }
            let external = document
                .aliases_of(&anchor.name)
                .iter()
                .filter(|alias| alias.mark_span.0 < start || alias.mark_span.1 > end)
                .count();
            if external > 0 {
                return Err(shared_by_aliases_refused(
                    target,
                    target,
                    &anchor.name,
                    external,
                    operation,
                ));
            }
        }
    }
    Ok(())
}

/// The anchor attached to the node whose value starts at `value_start` when
/// aliases refer to it, and how many. An anchor mark sits directly in front of
/// the value it names, with nothing but whitespace between.
fn anchor_with_sites(
    document: &noyalib::cst::Document,
    content: &str,
    value_start: usize,
) -> Option<(String, usize)> {
    document.anchors().into_iter().find_map(|anchor| {
        // The reported value span may begin at the mark itself or just after it.
        let attached = anchor.mark_span.0 == value_start
            || content
                .get(anchor.mark_span.1..value_start)
                .is_some_and(|between| between.trim().is_empty());
        if !attached {
            return None;
        }
        let sites = document.aliases_of(&anchor.name).len();
        (sites > 0).then_some((anchor.name, sites))
    })
}

fn guard_cst_segments(
    content: &str,
    segments: &[String],
    operation: &str,
    allow_missing: bool,
) -> DocumentResult<()> {
    let root = load(content)?;
    let mut current = &root;
    for (index, segment) in segments.iter().enumerate() {
        match current {
            Value::Object(object) => {
                if segment.parse::<usize>().is_ok() || segment.contains(['[', ']']) {
                    return Err(DocumentError::UnsupportedOperation {
                        format: "YAML".to_string(),
                        operation: operation.to_string(),
                        detail: format!(
                            "mapping key `{segment}` is ambiguous in the CST path grammar"
                        ),
                    });
                }
                match object.get(segment) {
                    Some(next) => current = next,
                    None if allow_missing => {
                        if segments[index..]
                            .iter()
                            .any(|part| part.parse::<usize>().is_ok() || part.contains(['[', ']']))
                        {
                            return Err(DocumentError::UnsupportedOperation {
                                format: "YAML".to_string(),
                                operation: operation.to_string(),
                                detail: "a missing mapping chain contains a CST-ambiguous key"
                                    .to_string(),
                            });
                        }
                        return Ok(());
                    }
                    None => {
                        return Err(DocumentError::PathNotFound {
                            path: crate::document::join_path(&segments[..=index]),
                        });
                    }
                }
            }
            Value::Array(values) => {
                let array_index =
                    segment
                        .parse::<usize>()
                        .map_err(|_| DocumentError::UnregisteredArray {
                            path: crate::document::join_path(&segments[..index]),
                        })?;
                current =
                    values
                        .get(array_index)
                        .ok_or_else(|| DocumentError::IndexOutOfBounds {
                            path: crate::document::join_path(&segments[..index]),
                            index: array_index,
                            len: values.len(),
                        })?;
            }
            value => {
                return Err(DocumentError::NotTraversable {
                    path: crate::document::join_path(&segments[..index]),
                    got: value.kind_name().to_string(),
                });
            }
        }
    }
    Ok(())
}

fn to_noyalib_value(value: &Value) -> DocumentResult<YamlValue> {
    match value {
        Value::Null => Ok(YamlValue::Null),
        Value::Bool(value) => Ok(YamlValue::Bool(*value)),
        Value::Integer(value) => Ok(YamlValue::from(*value)),
        Value::Unsigned(value) => Ok(YamlValue::from(*value)),
        Value::Float(value) if value.is_finite() => Ok(YamlValue::from(*value)),
        Value::Float(_) => Err(DocumentError::UnsupportedOperation {
            format: "YAML".to_string(),
            operation: "set".to_string(),
            detail: "non-finite YAML float is not representable".to_string(),
        }),
        // See the identical fallback in `format::toml::toml_item`: a
        // float-shaped `Value::Number` literal parses to `f64` cleanly (YAML
        // floats are canonically `f64` at the format level too); an
        // integer-shaped one only exists because it overflows `u64`, so it
        // can never be written through noyalib's numeric `Value`.
        Value::Number(text) if value.is_float() => text
            .parse::<f64>()
            .ok()
            .filter(|value| value.is_finite())
            .map(YamlValue::from)
            .ok_or_else(|| DocumentError::UnsupportedOperation {
                format: "YAML".to_string(),
                operation: "set".to_string(),
                detail: "float literal is not representable in YAML".to_string(),
            }),
        Value::Number(_) => Err(DocumentError::UnsupportedOperation {
            format: "YAML".to_string(),
            operation: "set".to_string(),
            detail: "integer literal exceeds YAML's 64-bit integer range".to_string(),
        }),
        Value::String(value) => Ok(YamlValue::String(value.clone())),
        Value::Array(values) => Ok(YamlValue::Sequence(
            values
                .iter()
                .map(to_noyalib_value)
                .collect::<DocumentResult<Vec<_>>>()?,
        )),
        Value::Object(values) => {
            let mut mapping = YamlMapping::new();
            for (key, value) in values {
                mapping.insert(key.clone(), to_noyalib_value(value)?);
            }
            Ok(YamlValue::Mapping(mapping))
        }
    }
}

pub fn save(value: &Value) -> DocumentResult<String> {
    render(value, None)
}

/// `value` as one line of flow YAML (`["a\x7Fb"]`), for filling an empty
/// flow collection in place. Emitted by noyalib like every other fragment, so
/// a scalar YAML forbids raw (DEL, C1 controls) is escaped rather than written
/// into source the reader would then reject, and exact numbers keep their
/// spelling.
fn flow_fragment(value: &Value) -> DocumentResult<String> {
    let config = noyalib::SerializerConfig::new().flow_style(noyalib::FlowStyle::Flow);
    let rendered = render(value, Some(&config))?;
    let line = rendered.trim_end_matches(['\r', '\n']);
    if line.contains('\n') {
        return Err(DocumentError::UnsupportedOperation {
            format: "YAML".to_string(),
            operation: "add".to_string(),
            detail: "the item has no single-line flow spelling".to_string(),
        });
    }
    Ok(line.to_string())
}

fn render(value: &Value, config: Option<&noyalib::SerializerConfig>) -> DocumentResult<String> {
    let mut prefix = "__AFDATA_EXACT_NUMBER_".to_string();
    while value_contains_text(value, &prefix) {
        prefix.push('_');
    }
    let mut literals = Vec::new();
    let yaml_val = our_value_to_yaml_value(value, &prefix, &mut literals)?;
    let rendered = match config {
        Some(config) => noyalib::to_string_value_with_config(&yaml_val, config),
        None => to_string(&yaml_val),
    };
    let mut output = rendered.map_err(|e| DocumentError::ParseError {
        format: "YAML".to_string(),
        detail: e.to_string(),
    })?;
    for (sentinel, literal) in literals {
        output = output.replace(&sentinel, &literal);
    }
    Ok(output)
}

fn value_to_our_value(v: YamlValue, literals: &std::collections::HashMap<String, String>) -> Value {
    match v {
        YamlValue::Null => Value::Null,
        YamlValue::Bool(b) => Value::Bool(b),
        YamlValue::Number(n) => {
            if let Some(i) = n.as_i64() {
                Value::Integer(i)
            } else if let Some(u) = n.as_u64() {
                Value::Unsigned(u)
            } else {
                Value::Float(n.as_f64())
            }
        }
        YamlValue::String(s) => literals
            .get(&s)
            .cloned()
            .map(Value::Number)
            .unwrap_or(Value::String(s)),
        YamlValue::Sequence(seq) => Value::Array(
            seq.into_iter()
                .map(|value| value_to_our_value(value, literals))
                .collect(),
        ),
        YamlValue::Mapping(map) => {
            let mut obj = std::collections::BTreeMap::new();
            for (key, value) in map {
                let key = literals.get(&key).cloned().unwrap_or(key);
                obj.insert(key, value_to_our_value(value, literals));
            }
            Value::Object(obj)
        }
        YamlValue::Tagged(t) => {
            // Tagged values: recurse on inner value
            let (_, value) = t.into_parts();
            value_to_our_value(value, literals)
        }
    }
}

fn our_value_to_yaml_value(
    v: &Value,
    prefix: &str,
    literals: &mut Vec<(String, String)>,
) -> DocumentResult<YamlValue> {
    match v {
        Value::Null => Ok(YamlValue::Null),
        Value::Bool(b) => Ok(YamlValue::Bool(*b)),
        Value::Integer(i) => Ok(YamlValue::Number((*i).into())),
        Value::Unsigned(i) => Ok(YamlValue::Number((*i).into())),
        Value::Float(f) if f.is_finite() => Ok(YamlValue::Number((*f).into())),
        Value::Float(_) => Err(DocumentError::UnsupportedOperation {
            format: "YAML".to_string(),
            operation: "save".to_string(),
            detail: "non-finite float is not representable in YAML".to_string(),
        }),
        Value::Number(text) => {
            if !is_json_number(text) {
                return Err(DocumentError::UnsupportedOperation {
                    format: "YAML".to_string(),
                    operation: "save".to_string(),
                    detail: "invalid number literal".to_string(),
                });
            }
            let sentinel = format!("{prefix}{}__", literals.len());
            literals.push((sentinel.clone(), text.clone()));
            Ok(YamlValue::String(sentinel))
        }
        Value::String(s) => Ok(YamlValue::String(protect_yaml_string(s, prefix, literals))),
        Value::Array(a) => {
            let seq = a
                .iter()
                .map(|value| our_value_to_yaml_value(value, prefix, literals))
                .collect::<DocumentResult<Vec<_>>>()?;
            Ok(YamlValue::Sequence(seq))
        }
        Value::Object(o) => {
            let mut mapping = YamlMapping::new();
            for (k, v) in o {
                mapping.insert(
                    protect_yaml_string(k, prefix, literals),
                    our_value_to_yaml_value(v, prefix, literals)?,
                );
            }
            Ok(YamlValue::Mapping(mapping))
        }
    }
}

fn quoted_yaml_string(text: &str) -> String {
    format!("\"{}\"", crate::formatting::escape_yaml_str(text))
}

fn protect_yaml_string(text: &str, prefix: &str, literals: &mut Vec<(String, String)>) -> String {
    if yaml_needs_legacy_quotes(text) {
        let placeholder = format!("{prefix}{}__", literals.len());
        literals.push((placeholder.clone(), quoted_yaml_string(text)));
        placeholder
    } else {
        text.to_owned()
    }
}

/// Strings whose plain spelling can resolve to a non-string under YAML 1.1.
fn yaml_needs_legacy_quotes(text: &str) -> bool {
    let lower = text.to_ascii_lowercase();
    if matches!(
        lower.as_str(),
        "" | "y" | "n" | "yes" | "no" | "on" | "off" | "true" | "false" | "null" | "~"
    ) {
        return true;
    }
    let unsigned = lower.strip_prefix(['+', '-']).unwrap_or(&lower);
    if matches!(unsigned, ".inf" | ".nan") {
        return true;
    }
    let number = unsigned.replace('_', "");
    if number.starts_with(|c: char| c.is_ascii_digit() || c == '.')
        && (number.parse::<f64>().is_ok()
            || ["0b", "0o", "0x"]
                .into_iter()
                .zip([2, 8, 16])
                .any(|(prefix, radix)| {
                    number.strip_prefix(prefix).is_some_and(|digits| {
                        !digits.is_empty() && digits.chars().all(|c| c.is_digit(radix))
                    })
                })
            || number.split_once(':').is_some_and(|(first, rest)| {
                !first.is_empty()
                    && first.bytes().all(|c| c.is_ascii_digit())
                    && rest.split(':').all(|part| part.parse::<f64>().is_ok())
            }))
    {
        return true;
    }
    text.as_bytes().get(4) == Some(&b'-')
        && text.as_bytes()[..4].iter().all(u8::is_ascii_digit)
        && text[5..].split_once('-').is_some_and(|(month, day)| {
            (1..=2).contains(&month.len())
                && month.bytes().all(|c| c.is_ascii_digit())
                && day.starts_with(|c: char| c.is_ascii_digit())
        })
}

/// Typed CST insertion may choose its own flow or block emitter. Apply the
/// same legacy-scalar rule to the inserted subtree while leaving siblings
/// and existing keys byte-for-byte intact.
fn quote_inserted_scalars(document: &noyalib::cst::Document, path: &str) -> String {
    let source = document.source();
    let mut spans = Vec::new();
    if let Some((start, end)) = document.key_span(path)
        && yaml_needs_legacy_quotes(&source[start..end])
    {
        spans.push((start, end));
    }
    if let Some((start, end)) = document.span_at(path) {
        collect_legacy_string_spans(document.syntax(), source, 0, start..end, &mut spans);
    }
    let mut output = source.to_owned();
    for (start, end) in spans.into_iter().rev() {
        output.replace_range(start..end, &quoted_yaml_string(&source[start..end]));
    }
    output
}

fn collect_legacy_string_spans(
    node: &GreenNode,
    source: &str,
    mut offset: usize,
    range: std::ops::Range<usize>,
    spans: &mut Vec<(usize, usize)>,
) {
    for child in node.children() {
        let end = offset + child.text_len();
        if offset < range.end && end > range.start {
            match child {
                GreenChild::Node(node) => {
                    collect_legacy_string_spans(node, source, offset, range.clone(), spans)
                }
                GreenChild::Token {
                    kind: SyntaxKind::PlainScalar,
                    ..
                } if offset >= range.start => {
                    let text = source[offset..end].trim_end();
                    if yaml_needs_legacy_quotes(text)
                        && noyalib::from_str::<YamlValue>(text)
                            .is_ok_and(|value| matches!(value, YamlValue::String(_)))
                    {
                        spans.push((offset, offset + text.len()));
                    }
                }
                _ => {}
            }
        }
        offset = end;
    }
}

fn yaml_fragment(value: &Value, operation: &str) -> DocumentResult<String> {
    if let Value::String(text) = value
        && yaml_needs_legacy_quotes(text)
    {
        return Ok(quoted_yaml_string(text));
    }
    if let Value::Number(text) = value
        && is_json_number(text)
    {
        return Ok(text.clone());
    }
    if matches!(value, Value::Array(_) | Value::Object(_)) {
        return save(value);
    }
    to_string(&to_noyalib_value(value)?).map_err(|error| DocumentError::UnsupportedOperation {
        format: "YAML".to_string(),
        operation: operation.to_string(),
        detail: error.to_string(),
    })
}

fn protect_exact_numbers(
    content: &str,
) -> DocumentResult<(String, std::collections::HashMap<String, String>)> {
    let document = parse_document(content).map_err(|error| match error {
        noyalib::Error::MoreThanOneDocument => {
            let first_end = noyalib::cst::parse_stream(content).ok()
                .and_then(|documents| documents.first().map(|document| document.source().len()));
            let line = first_end.map(|end| content[..end].lines().count() + 1);
            DocumentError::SourceRefused {
                format: "YAML".to_string(),
                detail: match line {
                    Some(line) => format!("multiple documents are not supported (second document starts near line {line})"),
                    None => "multiple documents are not supported".to_string(),
                },
            }
        }
        other => DocumentError::ParseError { format: "YAML".to_string(), detail: other.to_string() },
    })?;
    let mut spans = Vec::new();
    collect_exact_number_spans(document.syntax(), content, 0, &mut spans);
    let mut prefix = "__AFDATA_EXACT_NUMBER_".to_string();
    while content.contains(&prefix) {
        prefix.push('_');
    }
    let mut protected = content.to_string();
    let mut literals = std::collections::HashMap::new();
    for (index, (start, end)) in spans.into_iter().enumerate().rev() {
        let literal = content[start..end].to_string();
        let sentinel = format!("{prefix}{index}__");
        let quoted =
            serde_json::to_string(&sentinel).map_err(|error| DocumentError::ParseError {
                format: "YAML".to_string(),
                detail: error.to_string(),
            })?;
        protected.replace_range(start..end, &quoted);
        literals.insert(sentinel, literal);
    }
    Ok((protected, literals))
}

fn collect_exact_number_spans(
    node: &GreenNode,
    source: &str,
    base: usize,
    spans: &mut Vec<(usize, usize)>,
) {
    let mut offset = base;
    for child in node.children() {
        match child {
            GreenChild::Node(node) => collect_exact_number_spans(node, source, offset, spans),
            GreenChild::Token {
                kind: SyntaxKind::PlainScalar,
                len,
            } => {
                let token_end = offset + *len as usize;
                let text = source[offset..token_end].trim_end_matches([' ', '\t', '\r', '\n']);
                let end = offset + text.len();
                if should_preserve_number(text) {
                    spans.push((offset, end));
                }
            }
            GreenChild::Token { .. } => {}
        }
        offset += child.text_len();
    }
}

fn should_preserve_number(text: &str) -> bool {
    if !is_json_number(text) {
        return false;
    }
    text.contains(['.', 'e', 'E']) || (text.parse::<i64>().is_err() && text.parse::<u64>().is_err())
}

fn is_json_number(text: &str) -> bool {
    serde_json::from_str::<serde_json::Value>(text).is_ok_and(|value| value.is_number())
}

fn value_contains_text(value: &Value, needle: &str) -> bool {
    match value {
        Value::Number(text) | Value::String(text) => text.contains(needle),
        Value::Array(values) => values
            .iter()
            .any(|value| value_contains_text(value, needle)),
        Value::Object(values) => values
            .iter()
            .any(|(key, value)| key.contains(needle) || value_contains_text(value, needle)),
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use super::{load, save, set_preserving};
    use crate::document::Value;

    #[test]
    fn new_fields_in_flow_mappings_preserve_their_exact_value_and_source() {
        use crate::document::{Document, Format};
        for (source, path) in [
            ("{}\n", "field"),
            ("{existing: before}\n", "field"),
            ("outer: {}\n", "outer.field"),
            ("# keep\r\n{}\r\n", "field"),
        ] {
            for value in [
                Value::String("new".into()),
                Value::Bool(true),
                Value::Null,
                Value::Integer(7),
                Value::Unsigned(7),
                Value::Float(2.0),
                Value::Array(Vec::new()),
                Value::Object(Default::default()),
                Value::Number("123456789012345678901234567890".into()),
                Value::Number("0.10000000000000000000001".into()),
            ] {
                let mut document = Document::parse(source, Format::Yaml).unwrap();
                document
                    .set(path, value.clone())
                    .expect("insert into a flow mapping");
                assert_eq!(document.value_at(path).unwrap(), value);
                assert_eq!(
                    load(document.source()).unwrap(),
                    load(&save(document.value()).unwrap()).unwrap()
                );
                if source.starts_with("# keep") {
                    assert!(document.source().starts_with("# keep\r\n"));
                    assert!(document.source().ends_with("\r\n"));
                }
            }
        }
    }

    #[test]
    fn a_refused_key_cannot_fall_back_to_inserting_multiple_entries() {
        use crate::document::{Document, Format};
        let source = "attachments:\n";
        let mut document = Document::parse(source, Format::Yaml).unwrap();
        let original = document.value().clone();
        assert!(
            document
                .set("one:\ntwo", Value::String("injected".into()))
                .is_err()
        );
        assert_eq!(document.source(), source);
        assert_eq!(document.value(), &original);
    }

    #[test]
    fn preserves_large_integer_and_high_precision_float_literals() {
        let source = concat!(
            "huge: 123456789012345678901234567890\n",
            "precise: 0.1000000000000000055511151231257827\n",
        );
        let value = load(source).expect("load");
        assert_eq!(
            value.get("huge"),
            Some(&Value::Number("123456789012345678901234567890".to_string()))
        );
        assert_eq!(
            value.get("precise"),
            Some(&Value::Number(
                "0.1000000000000000055511151231257827".to_string()
            ))
        );

        let rendered = save(&value).expect("save");
        assert!(rendered.contains("123456789012345678901234567890"));
        assert!(rendered.contains("0.1000000000000000055511151231257827"));
        assert_eq!(load(&rendered).expect("reload"), value);
    }

    #[test]
    fn exact_number_set_keeps_the_literal() {
        let edited = set_preserving(
            "price: 1.0\n",
            "price",
            &Value::Number("12345678901234567890.123456789".to_string()),
        )
        .expect("set");
        assert_eq!(edited, "price: 12345678901234567890.123456789\n");
        assert_eq!(
            load(&edited).expect("reload").get("price"),
            Some(&Value::Number("12345678901234567890.123456789".to_string()))
        );
    }

    /// The shape that motivated the fragment editor: a frontmatter block a
    /// human has edited, where one collection field changes.
    fn contact_source() -> &'static str {
        "# a leading comment\ndisplay_name: Alice Example\nkind: contact\nemails:\n  - alice@example.com  # work\ntags: []\nrole: ''\n"
    }

    #[test]
    fn replacing_a_collection_keeps_every_other_byte() {
        let edited = set_preserving(
            contact_source(),
            "tags",
            &Value::Array(vec![Value::String("vip".into())]),
        )
        .expect("an empty sequence can grow");
        assert_eq!(
            edited,
            "# a leading comment\ndisplay_name: Alice Example\nkind: contact\nemails:\n  - alice@example.com  # work\ntags:\n  - vip\nrole: ''\n"
        );

        // Back to empty, and the inline spelling returns rather than a bare key
        // (which would parse as null) or a two-line `tags:\n  []`.
        let cleared = set_preserving(&edited, "tags", &Value::Array(Vec::new()))
            .expect("a sequence can shrink to empty");
        assert_eq!(cleared, contact_source());
    }

    #[test]
    fn replacing_a_collection_quotes_elements_that_need_it() {
        let edited = set_preserving(
            contact_source(),
            "tags",
            &Value::Array(vec![
                Value::String("true".into()),
                Value::String("123".into()),
                Value::String("a: b".into()),
                Value::String("#c".into()),
                Value::String(String::new()),
            ]),
        )
        .expect("tricky scalars are the emitter's problem, not ours");
        // Round-trips as the strings that went in, not as bool/int/comment.
        let loaded = load(&edited).expect("the result parses");
        assert_eq!(
            crate::document::get_path(&loaded, "tags", crate::document::Addressing::INDEX_ONLY)
                .expect("tags"),
            Value::Array(vec![
                Value::String("true".into()),
                Value::String("123".into()),
                Value::String("a: b".into()),
                Value::String("#c".into()),
                Value::String(String::new()),
            ])
        );
    }

    #[test]
    fn replacing_a_collection_takes_the_comment_that_described_it() {
        // The CST's span stops before a trailing comment, so leaving it in
        // place would re-point `# work` at whatever the new last element is.
        let edited = set_preserving(
            "emails:\n  - alice@example.com  # work\nrole: ''\n",
            "emails",
            &Value::Array(vec![Value::String("bob@example.com".into())]),
        )
        .expect("replace");
        assert_eq!(edited, "emails:\n  - bob@example.com\nrole: ''\n");
        assert!(!edited.contains("# work"), "{edited}");
    }

    #[test]
    fn a_collection_reached_through_an_alias_is_refused() {
        // `span_at` resolves through the alias to the anchor, so an unguarded
        // splice would rewrite `base` when asked for `other`.
        let source = "base: &b\n  - x\nother: *b\n";
        let error = set_preserving(
            source,
            "other",
            &Value::Array(vec![Value::String("y".into())]),
        )
        .expect_err("an alias target must not be edited through");
        assert!(error.to_string().contains("alias"), "{error}");
    }

    #[test]
    fn a_new_key_can_be_created_with_a_collection_value() {
        let edited = set_preserving(
            "kind: contact\n",
            "tags",
            &Value::Array(vec![Value::String("vip".into())]),
        )
        .expect("a missing key is inserted");
        assert_eq!(edited, "kind: contact\ntags:\n  - vip\n");

        let empty = set_preserving("kind: contact\n", "tags", &Value::Array(Vec::new()))
            .expect("a missing key can be inserted empty");
        assert_eq!(empty, "kind: contact\ntags: []\n");
    }

    #[test]
    fn replacing_a_collection_keeps_the_source_newline_style() {
        let edited = set_preserving(
            "kind: contact\r\ntags: []\r\nrole: ''\r\n",
            "tags",
            &Value::Array(vec![Value::String("vip".into())]),
        )
        .expect("CRLF source");
        assert_eq!(edited, "kind: contact\r\ntags:\r\n  - vip\r\nrole: ''\r\n");
        // No lone LF survives once every CRLF is accounted for.
        assert!(
            !edited.replace("\r\n", "").contains('\n'),
            "mixed endings: {edited:?}"
        );
    }

    #[test]
    fn a_new_key_lands_after_a_bare_null_last_entry() {
        // A mapping whose last entry has no value node (`attachments:` reads as
        // null) gives the CST nothing to anchor an insertion to.
        let source = "kind: draft\nattachments:\n";
        let edited = set_preserving(source, "sync_intent", &Value::String("send".into()))
            .expect("a new key can follow a bare-null entry");
        assert_eq!(edited, "kind: draft\nattachments:\nsync_intent: send\n");
    }

    #[test]
    fn save_rejects_non_finite_float() {
        let error = save(&Value::Float(f64::NAN)).expect_err("NaN must fail");
        assert!(error.to_string().contains("non-finite"));
    }
}