agent-first-data 0.36.1

A naming convention that lets AI agents understand your data without being told what it means, plus the afdata CLI and a Rust library for reading Markdown structure and safely editing structured JSON, TOML, YAML, dotenv, and INI documents.
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
//! Markdown mode: read a CommonMark file as a tree of heading sections.
//! Read-only — Markdown prose is never written back.
//!
//! A heading owns everything under it until the next heading of its own level
//! or shallower, so the document becomes a tree. Each section reports its
//! heading `text` and `level`, its own `blocks` in source order, the
//! `paragraph` subset of those, and its child sections under `h2`/`h3`/…
//! Anything before the first heading is `preamble`, which carries the same
//! `blocks`/`paragraph` pair.
//!
//! ```text
//! preamble.blocks.0   → { type: "frontmatter", format: "toml", text: "" }
//! preamble.paragraph.0 → { type: "paragraph", text: "CI" }       (a badge line)
//! h1.0.text           → "Real"
//! h1.0.paragraph.0    → { type: "paragraph", text: "The lead." }
//! h1.0.blocks.1       → { type: "code", language: "bash", text: "…" }
//! h1.0.h2.0.text      → "A quick look"
//! ```
//!
//! Segments are matched by content as well as by index (see
//! [`Format::array_rule`](crate::document::Format::array_rule)): `h2.look`
//! finds the section headed "A quick look", and matching several sections is an
//! error rather than a guess. That is what makes an address survive editing —
//! `h2.3` moves the moment a section is inserted above it, and a top-level
//! index moves the moment a badge line appears above the title.
//!
//! Sections are the reason the tree is not flat. A heading level is the one
//! piece of hierarchy CommonMark states outright, and folding on it costs
//! nothing while giving every address a stable frame: content is addressed
//! relative to the heading it lives under, not to the top of the file.
//!
//! What this backend owns is the *specification* layer — block identification,
//! block boundaries, and the heading nesting that follows from levels — and
//! nothing above it. Where a document's title lives, whether the first
//! paragraph is a synopsis, which blockquote carries a prompt: those are one
//! project's layout conventions, and they stay with the caller that holds them.
//! The distinction matters because block boundaries are precisely the part a
//! hand-rolled line scanner gets wrong: setext headings, the seven HTML-block
//! start conditions, four-space indented code, and the rule that an ATX heading
//! interrupts a paragraph are each a rule a `^# ` regex does not have.
//!
//! Detection is never automatic: a `.md` path resolves to no format on its own
//! and the caller must ask for `--input-format markdown`. The same file is
//! legitimately readable as `yaml-frontmatter`, and a reader that guesses
//! between two valid readings of one file is the shape-guessing AFDATA avoids.
//!
//! Deliberately out of scope, so that what this does return is exact:
//!
//! - **No dialects.** No GFM tables, footnotes, task lists, or strikethrough.
//!   A table's rows parse as a paragraph, which is the specification's answer,
//!   not a defect. (A leading `+++`/`---` metadata block *is* recognised, as
//!   its own block kind — see `options` for why that is not a dialect.)
//! - **No parsing or copying of frontmatter fields.** It is reported as one
//!   block with `format: "toml"|"yaml"` and empty `text`;
//!   `--input-format toml-frontmatter` is the reading that turns it into
//!   values. Omitting the raw metadata also prevents this structural reading
//!   from becoming a way around field-name-based secret redaction.
//! - **`text` is flattened plain text.** Emphasis is unwrapped, a code span
//!   keeps only its content, a link keeps its text, an image keeps its alt
//!   text, and inline HTML tags are dropped. What was flattened away is kept
//!   beside it: a paragraph, a heading, and a section report `inlines`, the
//!   ordered inline tree (`text`, `code`, `html`, `line_break`, and `emphasis`,
//!   `strong`, `link` with their own `inlines`; `link` and `image` carry
//!   `destination_url`). A blockquote, a list, and a list item report their
//!   child blocks under `blocks`, so a code fence inside a list item is still a
//!   `code` block. (Heading sections nest by level, not by walking a block.)
//! - **No byte offsets or columns.** Every block does carry 1-based inclusive
//!   `source_start_line` / `source_end_line`. Every section carries its whole
//!   source range plus `heading_end_line` for the
//!   heading alone. These are enough to splice whole Markdown blocks without
//!   making every consumer implement UTF-8 byte indexing.
//! - **No Markdown-to-Markdown transformation.** Rewriting a document in place
//!   needs source-preserving serialization, which is a separate design, not a
//!   rider on a reader.

use std::{collections::BTreeMap, ops::Range};

use pulldown_cmark::{CodeBlockKind, Event, MetadataBlockKind, Options, Parser, Tag};

use crate::document::{DocumentError, DocumentResult, Value};

/// Parse `content` as CommonMark into the section tree described above.
///
/// CommonMark has no invalid-input production — every UTF-8 string is some
/// sequence of blocks — so this fails only where afdata declines to answer: a
/// bare carriage return, or block nesting more than 48 levels deep. An
/// empty string yields an empty `preamble` and no sections.
pub fn load(content: &str) -> DocumentResult<Value> {
    reject_lone_carriage_return(content)?;
    let events: Vec<SpannedEvent<'_>> = Parser::new_ext(content, options())
        .into_offset_iter()
        .collect();
    reject_deep_nesting(&events)?;
    let lines = LineIndex::new(content);
    let mut cursor = 0;
    Ok(fold_sections(read_blocks(&events, &lines, &mut cursor)))
}

type SpannedEvent<'a> = (Event<'a>, Range<usize>);

/// Byte offsets of logical line starts, used only inside the parser boundary.
///
/// Public consumers see line numbers, not byte offsets. LF and CRLF input use
/// the same `\n`-based numbering as common line-oriented tools; a lone CR is
/// rejected before this index is constructed.
struct LineIndex<'a> {
    content: &'a str,
    starts: Vec<usize>,
}

impl<'a> LineIndex<'a> {
    /// Index the line starts of `content`, counting a line as everything up to
    /// the next `\n`.
    ///
    /// Not CommonMark's rule, deliberately. CommonMark also treats a bare `\r`
    /// as a line ending, and these numbers exist to be handed to something
    /// else — `sed -n '5,10p'`, `head -n`, an editor jump, a `git diff` — all
    /// of which split on `\n` alone. A number that only afdata can interpret
    /// is worse than no number: it looks usable and silently points one line
    /// off. CRLF agrees with both rules, so the two definitions differ only
    /// for a bare `\r`, which [`reject_lone_carriage_return`] refuses outright
    /// rather than reporting a line number nothing else can act on.
    fn new(content: &'a str) -> Self {
        let mut starts = vec![0];
        for (offset, byte) in content.bytes().enumerate() {
            if byte == b'\n' {
                starts.push(offset + 1);
            }
        }
        Self { content, starts }
    }

    fn number_at(&self, offset: usize) -> i64 {
        let line = self.starts.partition_point(|start| *start <= offset);
        i64::try_from(line).unwrap_or(i64::MAX)
    }

    /// The 1-based inclusive line range a source span covers.
    ///
    /// The span's trailing whitespace is dropped first. Most block kinds end
    /// at their own last character, but pulldown-cmark runs a list's span on
    /// to where the next block begins, so it carries the blank lines that
    /// separate them. A range is a splice instruction — a consumer cutting one
    /// out must not take the separator with it, or the blocks on either side
    /// merge (a lead paragraph absorbed into the setext heading below it).
    fn range(&self, source: &Range<usize>) -> SourceLines {
        let content_end = self
            .content
            .get(..source.end)
            .map_or(source.end, |head| head.trim_end().len())
            .max(source.start);
        let end_offset = content_end.saturating_sub(1).max(source.start);
        SourceLines {
            start: self.number_at(source.start),
            end: self.number_at(end_offset),
        }
    }
}

#[derive(Clone, Copy)]
struct SourceLines {
    start: i64,
    end: i64,
}

/// Refuse a document containing a bare `\r` — a carriage return not followed
/// by a newline.
///
/// This is the single case where CommonMark's line rule and every other tool's
/// disagree: CommonMark ends a line there, `sed`/`awk`/`wc`/`head`/`git` do
/// not. A reported line number is only useful if the thing the caller hands it
/// to counts the same way, and for such a file no single number can satisfy
/// both — two blocks would share one line, and a splice by that number would
/// cut the wrong text with nothing to notice it by.
///
/// So the file is refused instead of answered wrongly. It is the classic Mac
/// (pre-2002) line ending; CRLF and LF, which every current tool produces, are
/// unaffected because both rules agree on them.
fn reject_lone_carriage_return(content: &str) -> DocumentResult<()> {
    let bytes = content.as_bytes();
    for (offset, byte) in bytes.iter().enumerate() {
        if *byte == b'\r' && bytes.get(offset + 1) != Some(&b'\n') {
            return Err(DocumentError::SourceRefused {
                format: "Markdown".to_string(),
                detail: format!(
                    "a bare carriage return at byte {offset} ends a line for CommonMark but not \
                     for the tools these line numbers are meant to feed; convert the file to LF \
                     or CRLF line endings"
                ),
            });
        }
    }
    Ok(())
}

/// How deep blocks and inline spans may nest. The walk recurses once per
/// level, and the reported tree is deeper still: each level becomes an object
/// plus the array of its children, and the root and six heading levels add
/// about fifteen more. 48 keeps the deepest accepted file's tree near 111
/// levels, so it fits inside the 128 a JSON reader allows — serde_json's
/// limit, which `afdata get` applies to its own output read back — with room
/// for an envelope around it.
const MAX_BLOCK_DEPTH: usize = 48;

/// Refuse nesting the recursive walk cannot hold before it starts, so a file
/// of `> > > …` is an error rather than a stack overflow. Inline spans count
/// too: the reported inline tree nests exactly as deep as they do.
fn reject_deep_nesting(events: &[SpannedEvent<'_>]) -> DocumentResult<()> {
    let mut depth = 0usize;
    for (event, _) in events {
        match event {
            Event::Start(_) => {
                depth += 1;
                if depth > MAX_BLOCK_DEPTH {
                    return Err(DocumentError::SourceRefused {
                        format: "Markdown".to_string(),
                        detail: format!(
                            "blocks and inline spans nest deeper than {MAX_BLOCK_DEPTH} levels"
                        ),
                    });
                }
            }
            Event::End(_) => depth = depth.saturating_sub(1),
            _ => {}
        }
    }
    Ok(())
}

/// Pure CommonMark, plus the two metadata-block rules and nothing else.
///
/// The extensions that stay off are *dialects* — GFM tables, footnotes, task
/// lists, strikethrough each re-read text CommonMark already assigns a meaning
/// to, so enabling one is a guess about which flavour a file was written in.
///
/// A leading `+++`/`---` block is not that. afdata already treats frontmatter
/// as a first-class thing to read — `Format::TomlFrontmatter` and
/// `Format::YamlFrontmatter` exist — so a Markdown reader that took the same
/// bytes for prose would contradict the crate's own model, and did: a Zola
/// `_index.md` arrived with its `title = "…"` and `[extra]` lines flattened
/// into two paragraphs of the body. The block is only recognised at the very
/// start of the file, so it cannot reinterpret a `---` anywhere else (a setext
/// underline or a thematic break stays what it is).
fn options() -> Options {
    Options::ENABLE_YAML_STYLE_METADATA_BLOCKS | Options::ENABLE_PLUSES_DELIMITED_METADATA_BLOCKS
}

/// One heading and everything it owns, while the tree is still being built.
struct Section {
    level: i64,
    text: String,
    inlines: Value,
    heading_lines: SourceLines,
    blocks: Vec<Value>,
    children: Vec<Section>,
}

/// Fold a flat block sequence into the section tree.
///
/// A heading closes every open section at its own level or deeper, then opens
/// its own — the standard reading of heading levels, and the only hierarchy
/// CommonMark itself states. A level may be skipped (an `h3` directly under an
/// `h1`); the `h3` simply becomes a child of whatever section is open, since
/// there is no `h2` to hold it.
fn fold_sections(blocks: Vec<Value>) -> Value {
    let mut preamble = Vec::new();
    let mut roots: Vec<Section> = Vec::new();
    let mut open: Vec<Section> = Vec::new();

    for block in blocks {
        let heading_level = (block.get("type").and_then(Value::as_str) == Some("heading"))
            .then(|| block.get("level").and_then(Value::as_integer))
            .flatten();
        match heading_level {
            Some(level) => {
                while open.last().is_some_and(|section| section.level >= level) {
                    close_section(&mut open, &mut roots);
                }
                open.push(Section {
                    level,
                    text: block
                        .get("text")
                        .and_then(Value::as_str)
                        .unwrap_or_default()
                        .to_string(),
                    inlines: block
                        .get("inlines")
                        .cloned()
                        .unwrap_or_else(|| Value::Array(Vec::new())),
                    heading_lines: SourceLines {
                        start: block
                            .get("source_start_line")
                            .and_then(Value::as_integer)
                            .unwrap_or_default(),
                        end: block
                            .get("source_end_line")
                            .and_then(Value::as_integer)
                            .unwrap_or_default(),
                    },
                    blocks: Vec::new(),
                    children: Vec::new(),
                });
            }
            // Content before the first heading belongs to no section. It is
            // kept rather than dropped: "this file opens with a generated-file
            // comment" is a fact, and whether that is acceptable is the
            // caller's rule to apply, not this reader's to enforce by omission.
            None => match open.last_mut() {
                Some(section) => section.blocks.push(block),
                None => preamble.push(block),
            },
        }
    }
    while !open.is_empty() {
        close_section(&mut open, &mut roots);
    }

    // `preamble` carries the same two views a section does, so "the first
    // paragraph" is one address in both. As a bare array it was not: a `+++`
    // block or a badge line above the prose shifted every index, which is the
    // problem sections exist to remove.
    let mut root = BTreeMap::from([("preamble".to_string(), Value::Object(block_views(preamble)))]);
    insert_sections(&mut root, roots);
    Value::Object(root)
}

/// Pop the deepest open section and file it under its parent, or under the
/// document root when it has none.
fn close_section(open: &mut Vec<Section>, roots: &mut Vec<Section>) {
    let Some(done) = open.pop() else { return };
    match open.last_mut() {
        Some(parent) => parent.children.push(done),
        None => roots.push(done),
    }
}

/// File `sections` into `target` under `h1`/`h2`/… by their own level, each
/// group in source order.
fn insert_sections(target: &mut BTreeMap<String, Value>, sections: Vec<Section>) {
    for section in sections {
        let key = format!("h{}", section.level);
        let group = target
            .entry(key)
            .or_insert_with(|| Value::Array(Vec::new()));
        if let Some(items) = group.as_array_mut() {
            items.push(section.into_value());
        }
    }
}

/// The two views every block container reports: `blocks` in source order, and
/// the `paragraph` subset of them.
///
/// The subset is duplicated out of `blocks` on purpose. Prose is what a
/// container is usually read for, and "the first paragraph" must not shift
/// because a frontmatter block, a code fence, or a thematic break happened to
/// land above it. Badge syntax and a GFM-looking pipe table are paragraphs
/// under the deliberately enabled CommonMark grammar, so they remain in this
/// view. `blocks` stays the one place that shows what the container actually
/// looks like, in order.
fn block_views(blocks: Vec<Value>) -> BTreeMap<String, Value> {
    let of_kind = |kind: &str| {
        Value::Array(
            blocks
                .iter()
                .filter(|block| block.get("type").and_then(Value::as_str) == Some(kind))
                .cloned()
                .collect::<Vec<Value>>(),
        )
    };
    let paragraph = of_kind("paragraph");
    let blockquote = of_kind("blockquote");
    BTreeMap::from([
        ("paragraph".to_string(), paragraph),
        ("blockquote".to_string(), blockquote),
        ("blocks".to_string(), Value::Array(blocks)),
    ])
}

impl Section {
    fn into_value(self) -> Value {
        let source_end_line = self.source_end_line();
        let mut fields = block_views(self.blocks);
        fields.insert("level".to_string(), Value::Integer(self.level));
        fields.insert("text".to_string(), Value::String(self.text));
        fields.insert("inlines".to_string(), self.inlines);
        fields.insert(
            "source_start_line".to_string(),
            Value::Integer(self.heading_lines.start),
        );
        fields.insert(
            "source_end_line".to_string(),
            Value::Integer(source_end_line),
        );
        fields.insert(
            "heading_end_line".to_string(),
            Value::Integer(self.heading_lines.end),
        );
        insert_sections(&mut fields, self.children);
        Value::Object(fields)
    }

    fn source_end_line(&self) -> i64 {
        self.blocks
            .iter()
            .filter_map(|block| block.get("source_end_line"))
            .filter_map(Value::as_integer)
            .chain(self.children.iter().map(Section::source_end_line))
            .max()
            .unwrap_or(self.heading_lines.end)
    }
}

/// Read sibling blocks until the enclosing container's `End` event, or the end
/// of the stream at top level. Leaves `cursor` *on* that `End`, for the caller
/// that opened the container to consume.
fn read_blocks(
    events: &[SpannedEvent<'_>],
    lines: &LineIndex<'_>,
    cursor: &mut usize,
) -> Vec<Value> {
    let mut blocks = Vec::new();
    while let Some((event, source)) = events.get(*cursor) {
        match event {
            Event::End(_) => break,
            Event::Rule => {
                let source = source.clone();
                *cursor += 1;
                blocks.push(block("rule", String::new(), &source, lines, vec![]));
            }
            Event::Start(tag) if !is_inline_tag(tag) => {
                let source = source.clone();
                *cursor += 1;
                blocks.extend(read_block(tag, &source, events, lines, cursor));
            }
            // Inline content standing where a block belongs: a tight list's
            // item holds its text directly, with no paragraph around it.
            // Reading it as an implicit paragraph is what makes a tight and a
            // loose list report the same items.
            _ => {
                let first = *cursor;
                let (text, inlines) = read_loose_inline(events, cursor);
                if !text.is_empty() {
                    let source = covered_range(events, first, *cursor);
                    blocks.push(block(
                        "paragraph",
                        text,
                        &source,
                        lines,
                        vec![("inlines", inlines)],
                    ));
                }
            }
        }
    }
    blocks
}

/// Whether `tag` wraps text inside a block rather than opening one.
fn is_inline_tag(tag: &Tag<'_>) -> bool {
    matches!(
        tag,
        Tag::Emphasis
            | Tag::Strong
            | Tag::Strikethrough
            | Tag::Superscript
            | Tag::Subscript
            | Tag::Link { .. }
            | Tag::Image { .. }
    )
}

/// Read the one block opened by `tag`, consuming through its own `End`.
fn read_block(
    tag: &Tag<'_>,
    source: &Range<usize>,
    events: &[SpannedEvent<'_>],
    lines: &LineIndex<'_>,
    cursor: &mut usize,
) -> Option<Value> {
    match tag {
        Tag::Paragraph => {
            let (text, inlines) = read_inline(events, cursor);
            Some(block(
                "paragraph",
                text,
                source,
                lines,
                vec![("inlines", inlines)],
            ))
        }
        Tag::Heading { level, .. } => {
            let (text, inlines) = read_inline(events, cursor);
            Some(block(
                "heading",
                text,
                source,
                lines,
                vec![
                    ("level", Value::Integer(*level as i64)),
                    ("inlines", inlines),
                ],
            ))
        }
        Tag::CodeBlock(kind) => {
            // CommonMark's info string is everything after the opening fence;
            // in practice it is the language. An indented block has none.
            let info = match kind {
                CodeBlockKind::Fenced(info) => info.trim().to_string(),
                CodeBlockKind::Indented => String::new(),
            };
            Some(block(
                "code",
                read_verbatim(events, cursor),
                source,
                lines,
                // `language`, not CommonMark's `info`: a field must say what
                // it holds without its neighbours (spec/agent-first-data.md
                // rule 5, "Self-contained"). Sharing one name with the
                // frontmatter block below made `info: "toml"` mean either a
                // fence written in TOML or a `+++` delimiter, tellable apart
                // only by also reading `type`.
                vec![("language", Value::String(info))],
            ))
        }
        Tag::HtmlBlock => Some(block(
            "html",
            read_verbatim(events, cursor),
            source,
            lines,
            vec![],
        )),
        // The leading `+++`/`---` block, reported as its own kind without
        // copying its potentially secret-bearing source into `text`: which
        // fields it holds is TOML's or YAML's answer, and
        // `--input-format toml-frontmatter` is the reading that gives it.
        // `format` names the delimiter's dialect, matching the
        // `--input-format` token that reads its fields.
        Tag::MetadataBlock(kind) => {
            // Advance without collecting the metadata into a second String.
            // The source parser already borrows it, and this view deliberately
            // exposes neither a copy nor a flattened form.
            skip_subtree(events, cursor);
            Some(block(
                "frontmatter",
                String::new(),
                source,
                lines,
                vec![(
                    "format",
                    Value::String(
                        match kind {
                            MetadataBlockKind::PlusesStyle => "toml",
                            MetadataBlockKind::YamlStyle => "yaml",
                        }
                        .to_string(),
                    ),
                )],
            ))
        }
        Tag::BlockQuote(_) => {
            let (text, children) = read_container(events, lines, cursor);
            Some(block(
                "blockquote",
                text,
                source,
                lines,
                vec![("blocks", children)],
            ))
        }
        Tag::List(first_number) => {
            let (text, children) = read_container(events, lines, cursor);
            Some(block(
                "list",
                text,
                source,
                lines,
                vec![
                    ("ordered", Value::Bool(first_number.is_some())),
                    ("blocks", children),
                ],
            ))
        }
        // An item exists only as a list's child: it is reached through the
        // list's `blocks`, one `item` per list item, each with its own blocks.
        Tag::Item => {
            let (text, children) = read_container(events, lines, cursor);
            Some(block(
                "item",
                text,
                source,
                lines,
                vec![("blocks", children)],
            ))
        }
        // Tables, footnote definitions, definition lists, and metadata blocks
        // require options this backend does not enable, so none of them can
        // occur. Skipping the subtree keeps that a fact rather than a
        // half-formed block if the option set ever widens.
        _ => {
            skip_subtree(events, cursor);
            None
        }
    }
}

/// Flattened text of a container block — its child blocks' `text` joined by a
/// newline — and the child blocks themselves, consuming through the
/// container's own `End`.
///
/// Block boundaries survive as newlines because they are structure; a wrapped
/// line inside one paragraph does not, because it is presentation (see
/// [`read_inline`]). Children that flatten to nothing, such as a thematic
/// break, contribute nothing rather than a blank line.
fn read_container(
    events: &[SpannedEvent<'_>],
    lines: &LineIndex<'_>,
    cursor: &mut usize,
) -> (String, Value) {
    let children = read_blocks(events, lines, cursor);
    // `read_blocks` stops on the container's `End` rather than past it.
    *cursor += 1;
    let text = children
        .iter()
        .filter_map(|child| child.get("text").and_then(Value::as_str))
        .filter(|text| !text.is_empty())
        .collect::<Vec<_>>()
        .join("\n");
    (text, Value::Array(children))
}

/// Flattened plain text of a leaf block's inline content, and the inline tree
/// it was flattened from, consuming through that block's own `End`.
///
/// In `text`, emphasis and strong are unwrapped, a code span keeps its
/// content, a link keeps its text and drops its URL, an image keeps its alt
/// text, raw inline HTML tags are dropped, and every line break inside the
/// block — soft or hard — becomes a single space. The result is one line of
/// plain prose, which is what a name, a synopsis, or a prompt is. The tree
/// keeps what that dropped; see [`InlineReader`].
fn read_inline(events: &[SpannedEvent<'_>], cursor: &mut usize) -> (String, Value) {
    let read = read_loose_inline(events, cursor);
    if matches!(events.get(*cursor), Some((Event::End(_), _))) {
        *cursor += 1;
    }
    read
}

/// [`read_inline`] without an owning block: stops *before* the next block
/// boundary instead of consuming a closing `End`. This is the form a tight
/// list item needs, whose text has no paragraph of its own to end.
fn read_loose_inline(events: &[SpannedEvent<'_>], cursor: &mut usize) -> (String, Value) {
    let mut reader = InlineReader::default();
    let mut depth = 0usize;
    while let Some((event, _)) = events.get(*cursor) {
        match event {
            Event::Start(tag) if depth == 0 && !is_inline_tag(tag) => break,
            Event::End(_) if depth == 0 => break,
            Event::Rule if depth == 0 => break,
            Event::Start(tag) => {
                depth += 1;
                reader.open(tag);
            }
            Event::End(_) => {
                depth -= 1;
                reader.close();
            }
            Event::Text(chunk) => reader.text(chunk),
            Event::Code(chunk) => reader.leaf("code", chunk, chunk),
            Event::InlineHtml(chunk) | Event::Html(chunk) => reader.leaf("html", chunk, ""),
            Event::SoftBreak => reader.text(" "),
            Event::HardBreak => reader.leaf("line_break", "", " "),
            _ => {}
        }
        *cursor += 1;
    }
    reader.finish()
}

/// One inline node while its parent is still open.
struct Inline {
    kind: &'static str,
    /// Flattened text, under the same rule as the block's `text`.
    text: String,
    destination_url: Option<String>,
    /// `None` for a leaf, and for an image: alt text is plain text in the
    /// rendered output, so its markup is not reported as structure.
    children: Option<Vec<Inline>>,
}

impl Inline {
    fn into_value(self) -> Value {
        // A span's flattened text is trimmed like a block's; a leaf is not, or
        // the space between `see ` and a following link would be lost.
        let text = if self.children.is_some() || self.destination_url.is_some() {
            self.text.trim().to_string()
        } else {
            self.text
        };
        let mut fields = BTreeMap::from([
            ("type".to_string(), Value::String(self.kind.to_string())),
            ("text".to_string(), Value::String(text)),
        ]);
        if let Some(url) = self.destination_url {
            fields.insert("destination_url".to_string(), Value::String(url));
        }
        if let Some(children) = self.children {
            fields.insert("inlines".to_string(), inline_values(children));
        }
        Value::Object(fields)
    }
}

fn inline_values(inlines: Vec<Inline>) -> Value {
    Value::Array(inlines.into_iter().map(Inline::into_value).collect())
}

/// Builds a block's flattened `text` and its inline tree in one pass.
///
/// Every open span accumulates its own flattened text as content arrives, so
/// a link reports the text a reader sees without the caller walking its
/// children. Adjacent text — including a soft break, which is presentation —
/// merges into one `text` node. Spans that need a dialect this reader does not
/// enable (strikethrough, sub- and superscript) cannot occur; if one did, its
/// content would join its parent rather than invent a node kind.
#[derive(Default)]
struct InlineReader {
    text: String,
    roots: Vec<Inline>,
    open: Vec<Inline>,
    /// Per opened tag, whether it opened a node in `open`.
    opened: Vec<bool>,
}

impl InlineReader {
    /// The list new content joins. Never an image's: content inside one is
    /// only flattened (see `in_image`), so an image is never open here.
    fn siblings(&mut self) -> &mut Vec<Inline> {
        match self.open.last_mut() {
            Some(span) => span.children.get_or_insert_with(Vec::new),
            None => &mut self.roots,
        }
    }

    fn flatten(&mut self, chunk: &str) {
        self.text.push_str(chunk);
        for span in &mut self.open {
            span.text.push_str(chunk);
        }
    }

    fn in_image(&self) -> bool {
        self.open.iter().any(|span| span.kind == "image")
    }

    fn text(&mut self, chunk: &str) {
        self.flatten(chunk);
        if self.in_image() {
            return;
        }
        let siblings = self.siblings();
        match siblings.last_mut() {
            Some(last) if last.kind == "text" => last.text.push_str(chunk),
            _ => siblings.push(Inline {
                kind: "text",
                text: chunk.to_string(),
                destination_url: None,
                children: None,
            }),
        }
    }

    fn leaf(&mut self, kind: &'static str, node_text: &str, flat: &str) {
        self.flatten(flat);
        if self.in_image() {
            return;
        }
        self.siblings().push(Inline {
            kind,
            text: node_text.to_string(),
            destination_url: None,
            children: None,
        });
    }

    fn open(&mut self, tag: &Tag<'_>) {
        let span = match tag {
            Tag::Emphasis => Some(("emphasis", None, true)),
            Tag::Strong => Some(("strong", None, true)),
            Tag::Link { dest_url, .. } => Some(("link", Some(dest_url.to_string()), true)),
            Tag::Image { dest_url, .. } => Some(("image", Some(dest_url.to_string()), false)),
            _ => None,
        };
        // Inside an image everything is alt text: no nested nodes.
        let span = span.filter(|_| !self.in_image());
        self.opened.push(span.is_some());
        if let Some((kind, destination_url, structured)) = span {
            self.open.push(Inline {
                kind,
                text: String::new(),
                destination_url,
                children: structured.then(Vec::new),
            });
        }
    }

    fn close(&mut self) {
        if self.opened.pop() == Some(true)
            && let Some(done) = self.open.pop()
        {
            self.siblings().push(done);
        }
    }

    fn finish(mut self) -> (String, Value) {
        while !self.open.is_empty() {
            self.opened.push(true);
            self.close();
        }
        (self.text.trim().to_string(), inline_values(self.roots))
    }
}

/// Literal content of a code or HTML block, consuming through its `End`.
///
/// Nothing is flattened here — the content is not prose. The single trailing
/// newline every such block carries (the line break before its closing fence,
/// or ending its last line) is dropped; everything else is verbatim.
fn read_verbatim(events: &[SpannedEvent<'_>], cursor: &mut usize) -> String {
    let mut text = String::new();
    while let Some((event, _)) = events.get(*cursor) {
        *cursor += 1;
        match event {
            Event::End(_) => break,
            Event::Text(chunk) | Event::Html(chunk) => text.push_str(chunk),
            _ => {}
        }
    }
    let unterminated = text.strip_suffix('\n').unwrap_or(text.as_str());
    unterminated
        .strip_suffix('\r')
        .unwrap_or(unterminated)
        .to_string()
}

/// Consume an unhandled container's whole subtree, including its own `End`.
fn skip_subtree(events: &[SpannedEvent<'_>], cursor: &mut usize) {
    let mut depth = 0usize;
    while let Some((event, _)) = events.get(*cursor) {
        *cursor += 1;
        match event {
            Event::Start(_) => depth += 1,
            Event::End(_) => {
                if depth == 0 {
                    break;
                }
                depth -= 1;
            }
            _ => {}
        }
    }
}

/// The smallest source range covering events in `start..end`.
///
/// Top-level CommonMark blocks carry their full range on the opening event.
/// This fallback exists for inline text in tight containers, where there is no
/// paragraph `Start` event to lend us one.
fn covered_range(events: &[SpannedEvent<'_>], start: usize, end: usize) -> Range<usize> {
    let mut covered = events
        .get(start)
        .map(|(_, source)| source.clone())
        .unwrap_or(0..0);
    for (_, source) in events.get(start..end).unwrap_or_default() {
        covered.start = covered.start.min(source.start);
        covered.end = covered.end.max(source.end);
    }
    covered
}

/// Assemble one block: the `type`, flattened `text`, and 1-based inclusive
/// source-line range every block carries, plus kind-specific fields.
fn block(
    kind: &str,
    text: String,
    source: &Range<usize>,
    lines: &LineIndex<'_>,
    extra: Vec<(&str, Value)>,
) -> Value {
    let source = lines.range(source);
    let mut fields = BTreeMap::from([
        ("type".to_string(), Value::String(kind.to_string())),
        ("text".to_string(), Value::String(text)),
        (
            "source_start_line".to_string(),
            Value::Integer(source.start),
        ),
        ("source_end_line".to_string(), Value::Integer(source.end)),
    ]);
    for (name, value) in extra {
        fields.insert(name.to_string(), value);
    }
    Value::Object(fields)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::panic, clippy::expect_used)]
    use super::*;
    use crate::document::{Addressing, Format, get_path};

    /// Read one address exactly as a caller would, through the same traversal
    /// and the same format rule the CLI uses.
    fn at(source: &str, path: &str) -> DocumentResult<Value> {
        get_path(
            &load(source).unwrap(),
            path,
            Addressing::INDEX_ONLY.with_array_rule(Format::Markdown.array_rule()),
        )
    }

    fn text(source: &str, path: &str) -> String {
        at(source, path)
            .unwrap_or_else(|error| panic!("{path}: {error}"))
            .as_str()
            .unwrap_or_else(|| panic!("{path} is not a string"))
            .to_string()
    }

    fn integer(source: &str, path: &str) -> i64 {
        at(source, path)
            .unwrap_or_else(|error| panic!("{path}: {error}"))
            .as_integer()
            .unwrap_or_else(|| panic!("{path} is not an integer"))
    }

    /// `(type, text)` of a block array, which is what a caller reads.
    fn shape(source: &str, path: &str) -> Vec<(String, String)> {
        at(source, path)
            .unwrap_or_else(|error| panic!("{path}: {error}"))
            .as_array()
            .unwrap_or_else(|| panic!("{path} is not an array"))
            .iter()
            .map(|block| {
                let field = |name: &str| {
                    block
                        .get(name)
                        .and_then(Value::as_str)
                        .unwrap_or_default()
                        .to_string()
                };
                (field("type"), field("text"))
            })
            .collect()
    }

    fn types(source: &str, path: &str) -> Vec<String> {
        shape(source, path).into_iter().map(|(k, _)| k).collect()
    }

    // ---- the eight probes -------------------------------------------------
    //
    // These are the cases a hand-rolled line scanner answered wrong — all eight
    // of them. Each names the CommonMark rule it turns on, and each is the
    // classification a caller's layout policy then reads.

    #[test]
    fn probe_1_setext_heading_is_a_heading() {
        // An underlined title is a heading; `^# ` never sees it.
        let source = "Title\n=====\n\nThe lead.\n";
        assert_eq!(text(source, "h1.0.text"), "Title");
        assert_eq!(text(source, "h1.0.paragraph.0.text"), "The lead.");
    }

    #[test]
    fn probe_2_html_comment_before_the_heading_is_its_own_block() {
        // A generated-file banner is an HTML block. It lands in `preamble`,
        // where a caller can see it, and does not shift the title.
        let source = "<!-- generated -->\n\n# Real\n\nThe lead.\n";
        assert_eq!(
            shape(source, "preamble.blocks"),
            [("html".to_string(), "<!-- generated -->".to_string())]
        );
        assert_eq!(text(source, "h1.0.text"), "Real");
    }

    #[test]
    fn probe_3_badge_line_before_the_heading_is_a_paragraph() {
        // The most common README opening there is. A flat reading would make
        // this block 0 and publish `CI` as the project's name; here it is
        // preamble and the title is still `h1.0`.
        let source = "[![CI](a.svg)](b)\n\n# Real\n\nThe lead.\n";
        assert_eq!(
            shape(source, "preamble.blocks"),
            [("paragraph".to_string(), "CI".to_string())]
        );
        assert_eq!(text(source, "h1.0.text"), "Real");
        assert_eq!(text(source, "h1.0.paragraph.0.text"), "The lead.");
    }

    #[test]
    fn probe_4_fenced_code_in_the_lead_position_is_code() {
        // The section's first *block* is code, so `paragraph` is empty — a
        // caller asking for a synopsis gets a failure, not the code.
        let source = "# Real\n\n```bash\nafdata get x\n```\n";
        assert_eq!(
            shape(source, "h1.0.blocks"),
            [("code".to_string(), "afdata get x".to_string())]
        );
        assert_eq!(shape(source, "h1.0.paragraph"), []);
        assert_eq!(
            at(source, "h1.0.paragraph.0").unwrap_err().code(),
            "document_path_not_found"
        );
        assert_eq!(
            at(source, "h1.0.blocks.0.language").unwrap(),
            Value::String("bash".to_string())
        );
    }

    #[test]
    fn probe_5_leading_fence_swallows_the_heading_inside_it() {
        // `# Real` is code here, not a heading — so there is no section at all
        // and the whole file is preamble.
        let source = "```\n# Real\n```\n";
        assert_eq!(
            shape(source, "preamble.blocks"),
            [("code".to_string(), "# Real".to_string())]
        );
        assert_eq!(
            at(source, "h1.0").unwrap_err().code(),
            "document_path_not_found"
        );
    }

    #[test]
    fn probe_6_atx_heading_interrupts_a_paragraph() {
        // The rule that looks backwards and is not: a `# ` line ends the
        // paragraph it appears in rather than joining it. It also opens a
        // sibling section, so the lead stops there too.
        let source = "# Real\n\nThe lead.\n# looks like heading\nmore.\n";
        assert_eq!(text(source, "h1.0.text"), "Real");
        assert_eq!(
            shape(source, "h1.0.paragraph"),
            [("paragraph".to_string(), "The lead.".to_string())]
        );
        assert_eq!(text(source, "h1.1.text"), "looks like heading");
        assert_eq!(text(source, "h1.1.paragraph.0.text"), "more.");
    }

    #[test]
    fn probe_7_four_space_indent_is_code_not_a_heading() {
        // The worst of the eight: an indented `# Title` reads as a title to a
        // scanner that strips leading whitespace, and is code to CommonMark.
        let source = "    # Indented\n\nAfter.\n";
        assert_eq!(
            types(source, "preamble.blocks"),
            ["code".to_string(), "paragraph".to_string()]
        );
        assert_eq!(
            at(source, "h1.0").unwrap_err().code(),
            "document_path_not_found"
        );
    }

    #[test]
    fn probe_8_whole_paragraph_emphasis_is_unwrapped() {
        // Flattening gives this for free; a scanner needs a special case for
        // it, and still leaks the inner markers of the partial-emphasis form.
        assert_eq!(
            text("# Real\n\n**A bold tagline.**\n", "h1.0.paragraph.0.text"),
            "A bold tagline."
        );
        // Partial emphasis, a code span, and a link all flatten to plain text
        // too — the scanner leaked every one of these into published metadata.
        assert_eq!(
            text(
                "# T\n\nA **bold** `span` and a [link](https://example.com).\n",
                "h1.0.paragraph.0.text"
            ),
            "A bold span and a link."
        );
    }

    // ---- section folding --------------------------------------------------

    #[test]
    fn headings_nest_by_level() {
        let source = "# A\n\na.\n\n## B\n\nb.\n\n### C\n\nc.\n\n## D\n\nd.\n\n# E\n";
        assert_eq!(text(source, "h1.0.text"), "A");
        assert_eq!(text(source, "h1.0.paragraph.0.text"), "a.");
        assert_eq!(text(source, "h1.0.h2.0.text"), "B");
        assert_eq!(text(source, "h1.0.h2.0.h3.0.text"), "C");
        assert_eq!(text(source, "h1.0.h2.0.h3.0.paragraph.0.text"), "c.");
        // `D` closes `B` (same level) and `C` with it.
        assert_eq!(text(source, "h1.0.h2.1.text"), "D");
        assert_eq!(
            at(source, "h1.0.h2.1.h3.0").unwrap_err().code(),
            "document_path_not_found"
        );
        assert_eq!(text(source, "h1.1.text"), "E");
    }

    #[test]
    fn a_skipped_level_keeps_its_own_name() {
        // `### C` under `# A` with no `## ` between: C is A's child, filed by
        // its own level rather than promoted to one it does not have.
        let source = "# A\n\n### C\n\nc.\n";
        assert_eq!(text(source, "h1.0.h3.0.text"), "C");
        assert_eq!(
            at(source, "h1.0.h2.0").unwrap_err().code(),
            "document_path_not_found"
        );
    }

    #[test]
    fn a_document_opening_below_h1_has_no_h1() {
        // No invented level-1 wrapper: `h2` is simply where the sections are,
        // and a caller demanding `h1.0` fails loudly.
        let source = "## Only\n\ntext.\n";
        assert_eq!(text(source, "h2.0.text"), "Only");
        assert_eq!(
            at(source, "h1.0").unwrap_err().code(),
            "document_path_not_found"
        );
    }

    #[test]
    fn preamble_is_always_present_and_empty_for_a_clean_file() {
        assert_eq!(shape("# T\n\nlead\n", "preamble.blocks"), []);
        assert_eq!(shape("", "preamble.blocks"), []);
    }

    // ---- addressing by content --------------------------------------------

    #[test]
    fn a_section_is_addressable_by_a_word_of_its_heading() {
        let source = "# T\n\n## A Quick Look\n\ninside look.\n\n## Supported suffixes\n\ns.\n";
        // Case-insensitive substring: the memorable word, not the full text.
        assert_eq!(text(source, "h1.0.h2.look.text"), "A Quick Look");
        assert_eq!(
            text(source, "h1.0.h2.look.paragraph.0.text"),
            "inside look."
        );
        assert_eq!(text(source, "h1.0.h2.SUFFIX.text"), "Supported suffixes");
        // Content and index address the same section.
        assert_eq!(
            at(source, "h1.0.h2.look.text").unwrap(),
            at(source, "h1.0.h2.0.text").unwrap()
        );
        // Matching a body paragraph does not leak in: `h2` holds only headings,
        // which is the whole reason the tree is not flat.
        assert_eq!(
            at(source, "h1.0.h2.inside").unwrap_err().code(),
            "document_slug_not_found"
        );
    }

    #[test]
    fn an_empty_segment_is_not_an_address() {
        // `contains("")` is true for everything, so before this an empty
        // interpolated name resolved to whichever element happened to be
        // alone in the array — a confident wrong answer that only turned into
        // an error once a second element existed.
        let one = "# T\n\n## Only One\n\na\n";
        let two = "# T\n\n## A\n\na\n\n## B\n\nb\n";
        for source in [one, two] {
            assert_eq!(
                at(source, "h1.0.h2..text").unwrap_err().code(),
                "document_slug_not_found"
            );
        }
        // Named addressing still works.
        assert_eq!(text(two, "h1.0.h2.A.text"), "A");
    }

    #[test]
    fn a_word_matching_several_sections_is_refused() {
        let source = "# T\n\n## Quick look\n\na.\n\n## Another look\n\nb.\n";
        let error = at(source, "h1.0.h2.look").unwrap_err();
        assert_eq!(error.code(), "document_ambiguous_match");
        // The refusal reports structural indices, never matched document text.
        let message = error.to_string();
        assert!(message.contains("indices 0, 1"), "{message}");
        assert!(!message.contains("Quick look"), "{message}");
        assert!(!message.contains("Another look"), "{message}");
        // A word that separates them resolves.
        assert_eq!(text(source, "h1.0.h2.Another.text"), "Another look");
    }

    #[test]
    fn content_addressing_lowercases_unicode() {
        let source = "# T\n\n## Überblick\n\ninside.\n";
        assert_eq!(text(source, "h1.0.h2.ÜBER.text"), "Überblick");
    }

    #[test]
    fn the_ask_prompt_blockquote_is_addressable_by_its_opening_words() {
        // The real use: this blockquote sits at no fixed index in any README,
        // and its position moves with every edit above it.
        let source = "# T\n\nThe lead.\n\n> **Ask your agent:** \"Do the thing.\"\n";
        assert_eq!(
            text(source, "h1.0.blocks.Ask your agent.text"),
            "Ask your agent: \"Do the thing.\""
        );
    }

    // ---- inline flattening and block kinds --------------------------------

    #[test]
    fn wrapped_paragraph_joins_onto_one_line() {
        assert_eq!(
            text("# T\n\nLead line one\nline two.\n", "h1.0.paragraph.0.text"),
            "Lead line one line two."
        );
    }

    #[test]
    fn heading_level_is_reported_for_every_depth() {
        let source = "# a\n\n## b\n\n###### f\n";
        assert_eq!(at(source, "h1.0.level").unwrap(), Value::Integer(1));
        assert_eq!(at(source, "h1.0.h2.0.level").unwrap(), Value::Integer(2));
        assert_eq!(
            at(source, "h1.0.h2.0.h6.0.level").unwrap(),
            Value::Integer(6)
        );
    }

    #[test]
    fn blockquote_flattens_its_paragraphs() {
        // One wrapped paragraph is one line, as the prompt convention needs.
        assert_eq!(
            shape(
                "> **Ask your agent:** \"Wrapped across\n> two lines.\"\n",
                "preamble.blocks"
            ),
            [(
                "blockquote".to_string(),
                "Ask your agent: \"Wrapped across two lines.\"".to_string()
            )]
        );
        // Two paragraphs are two blocks, and that boundary is structure, so it
        // survives as a newline rather than dissolving into a space.
        assert_eq!(
            shape("> first\n>\n> second\n", "preamble.blocks"),
            [("blockquote".to_string(), "first\nsecond".to_string())]
        );
    }

    #[test]
    fn list_reports_its_items_and_whether_it_is_ordered() {
        let bullet = at("- one\n- two\n", "preamble.blocks.0").unwrap();
        assert_eq!(bullet.get("text").and_then(Value::as_str), Some("one\ntwo"));
        assert_eq!(bullet.get("ordered"), Some(&Value::Bool(false)));

        assert_eq!(
            at("1. one\n2. two\n", "preamble.blocks.0")
                .unwrap()
                .get("ordered"),
            Some(&Value::Bool(true))
        );

        // A loose list wraps each item in a paragraph and a tight one does
        // not. That is a rendering difference, not a content one, so the two
        // must read the same.
        assert_eq!(
            at("- one\n\n- two\n", "preamble.blocks.0")
                .unwrap()
                .get("text")
                .and_then(Value::as_str),
            Some("one\ntwo")
        );

        // A nested list is a block inside its item, and flattens with it.
        assert_eq!(
            at("- one\n  - inner\n- two\n", "preamble.blocks.0")
                .unwrap()
                .get("text")
                .and_then(Value::as_str),
            Some("one\ninner\ntwo")
        );
    }

    #[test]
    fn a_leading_metadata_block_is_its_own_kind() {
        // A Zola `_index.md`: the `+++` block used to flatten into two
        // paragraphs of the body, so `preamble` reported prose that was really
        // metadata and a caller reading "the first paragraph" got TOML.
        let toml = "+++\ntitle = \"T\"\n\n[extra]\ntagline = \"x\"\n+++\n\n# Real\n\nThe lead.\n";
        assert_eq!(types(toml, "preamble.blocks"), ["frontmatter".to_string()]);
        assert_eq!(
            at(toml, "preamble.blocks.0.format").unwrap(),
            Value::String("toml".to_string())
        );
        // Deliberately not copied into `text`: which fields it holds is TOML's
        // answer, and `--input-format toml-frontmatter` is how you get them.
        // This structural view must not bypass field-name-based redaction.
        assert_eq!(text(toml, "preamble.blocks.0.text"), "");
        // The body reads exactly as it would without the block.
        assert_eq!(text(toml, "h1.0.text"), "Real");
        assert_eq!(text(toml, "h1.0.paragraph.0.text"), "The lead.");

        let yaml = "---\ntitle: T\n---\n\n# Real\n";
        assert_eq!(types(yaml, "preamble.blocks"), ["frontmatter".to_string()]);
        assert_eq!(
            at(yaml, "preamble.blocks.0.format").unwrap(),
            Value::String("yaml".to_string())
        );
        assert_eq!(text(yaml, "h1.0.text"), "Real");
    }

    #[test]
    fn dashes_away_from_the_start_keep_their_commonmark_meaning() {
        // The metadata rule applies only at the very start of the file, so it
        // cannot reinterpret a `---` elsewhere. Both of these would break if
        // it did.
        assert_eq!(text("Setext\n---\n\nbody\n", "h2.0.text"), "Setext");
        assert_eq!(
            types("# T\n\na\n\n---\n\nb\n", "h1.0.blocks"),
            [
                "paragraph".to_string(),
                "rule".to_string(),
                "paragraph".to_string()
            ]
        );
    }

    #[test]
    fn a_source_range_stops_at_the_block_it_names() {
        // pulldown-cmark runs a list's span on to where the next block starts,
        // so it carries the blank separator. A range is a splice instruction:
        // taking the separator out merges the blocks on either side. Here that
        // made `Lead.` and `Next Title\n====` one setext heading, swallowing
        // the lead paragraph into a title.
        let source = "- a\n  - b\n\n\nAfter.\n";
        assert_eq!(
            at(source, "preamble.blocks.0.type").unwrap(),
            Value::String("list".to_string())
        );
        assert_eq!(
            at(source, "preamble.blocks.0.source_start_line").unwrap(),
            Value::Integer(1)
        );
        assert_eq!(
            at(source, "preamble.blocks.0.source_end_line").unwrap(),
            Value::Integer(2)
        );
        assert_eq!(
            at(source, "preamble.blocks.1.source_start_line").unwrap(),
            Value::Integer(5)
        );

        // Every other kind already ended at its own last line; assert they
        // still do, so the trim cannot over-correct.
        let mixed = "# H\n\npara\n\n```\ncode\n```\n\n> quote\n\n---\n\ntail\n";
        for (address, start, end) in [
            ("h1.0.blocks.0", 3, 3),
            ("h1.0.blocks.1", 5, 7),
            ("h1.0.blocks.2", 9, 9),
            ("h1.0.blocks.3", 11, 11),
            ("h1.0.blocks.4", 13, 13),
        ] {
            assert_eq!(
                at(mixed, &format!("{address}.source_start_line")).unwrap(),
                Value::Integer(start),
                "{address} start"
            );
            assert_eq!(
                at(mixed, &format!("{address}.source_end_line")).unwrap(),
                Value::Integer(end),
                "{address} end"
            );
        }
    }

    #[test]
    fn gfm_table_rows_are_a_paragraph() {
        // No extensions: a table is not a block kind here, and the pipe rows
        // are a paragraph. That is the specification's reading, not a gap.
        assert_eq!(
            shape("| a | b |\n|---|---|\n| 1 | 2 |\n", "preamble.blocks"),
            [(
                "paragraph".to_string(),
                "| a | b | |---|---| | 1 | 2 |".to_string()
            )]
        );
        assert_eq!(
            shape("| a | b |\n|---|---|\n| 1 | 2 |\n", "preamble.paragraph"),
            [(
                "paragraph".to_string(),
                "| a | b | |---|---| | 1 | 2 |".to_string()
            )]
        );
    }

    #[test]
    fn badge_syntax_remains_in_the_paragraph_view() {
        let source = "# T\n\n[![CI](a.svg)](b)\n\nThe lead.\n";
        assert_eq!(
            shape(source, "h1.0.paragraph"),
            [
                ("paragraph".to_string(), "CI".to_string()),
                ("paragraph".to_string(), "The lead.".to_string()),
            ]
        );
    }

    // ---- source line ranges ----------------------------------------------

    #[test]
    fn atx_heading_and_blocks_report_inclusive_source_lines() {
        let source = "# Title\n\nLead line one\nline two.\n\n```rs\nfn main() {}\n```\n";
        assert_eq!(integer(source, "h1.0.source_start_line"), 1);
        assert_eq!(integer(source, "h1.0.source_end_line"), 8);
        assert_eq!(integer(source, "h1.0.source_start_line"), 1);
        assert_eq!(integer(source, "h1.0.heading_end_line"), 1);
        assert_eq!(integer(source, "h1.0.paragraph.0.source_start_line"), 3);
        assert_eq!(integer(source, "h1.0.paragraph.0.source_end_line"), 4);
        assert_eq!(integer(source, "h1.0.blocks.1.source_start_line"), 6);
        assert_eq!(integer(source, "h1.0.blocks.1.source_end_line"), 8);
    }

    #[test]
    fn setext_heading_range_includes_its_underline() {
        let source = "My Project\n==========\n\nThe synopsis.\n\n## Install\n";
        assert_eq!(integer(source, "h1.0.source_start_line"), 1);
        assert_eq!(integer(source, "h1.0.heading_end_line"), 2);
        assert_eq!(integer(source, "h1.0.source_end_line"), 6);
        assert_eq!(integer(source, "h1.0.h2.0.source_start_line"), 6);
        assert_eq!(integer(source, "h1.0.h2.0.source_end_line"), 6);
        assert_eq!(integer(source, "h1.0.paragraph.0.source_start_line"), 4);
        assert_eq!(integer(source, "h1.0.paragraph.0.source_end_line"), 4);
    }

    #[test]
    fn line_ranges_are_utf8_safe_and_newline_style_independent() {
        let source = "# 中文标题\r\n\r\n这是首段,\r\n也是首段。\r\n\r\n## 安装";
        assert_eq!(integer(source, "h1.0.source_start_line"), 1);
        assert_eq!(integer(source, "h1.0.heading_end_line"), 1);
        assert_eq!(integer(source, "h1.0.paragraph.0.source_start_line"), 3);
        assert_eq!(integer(source, "h1.0.paragraph.0.source_end_line"), 4);
        assert_eq!(integer(source, "h1.0.h2.0.source_start_line"), 6);
        assert_eq!(integer(source, "h1.0.h2.0.heading_end_line"), 6);
    }

    #[test]
    fn nesting_beyond_the_block_depth_is_refused_not_a_stack_overflow() {
        let nested = |depth: usize| format!("# T\n{}x\n", "> ".repeat(depth));
        // The heading closes first, so the innermost paragraph adds one level.
        assert_eq!(text(&nested(47), "h1.0.blockquote.0.text"), "x");
        for depth in [48, 100_000] {
            let error = load(&nested(depth)).unwrap_err();
            assert_eq!(error.code(), "document_source_refused");
            assert!(error.to_string().contains("48 levels"), "{error}");
        }
        let error = load(&format!("{}x\n", "- ".repeat(100_000))).unwrap_err();
        assert_eq!(error.code(), "document_source_refused");
    }

    #[test]
    fn a_bare_carriage_return_is_refused_rather_than_numbered() {
        // CommonMark ends a line at a bare `\r`; sed, awk, wc, head, and git
        // do not. These numbers exist to be handed to those, so for such a
        // file no single number is right for both readers — here `Lead` and
        // `## End` would share a line, and a splice by that number would cut
        // the wrong text silently.
        let error = load("# T\r\rLead\rcontinued\r\r## End").unwrap_err();
        // Its own code, not `document_parse_failed`: the file is valid
        // CommonMark and afdata is declining to number it, so a reader told
        // "parse failed" would go hunting for a syntax error that is not there.
        assert_eq!(error.code(), "document_source_refused");
        assert!(error.to_string().contains("carriage return"), "{error}");
        // The way out survives redaction. This detail is written here, about
        // the file's line endings, and holds no document text — dropping it
        // left `failed to parse Markdown` and nothing to act on.
        assert!(
            error.redacted_message().contains("CRLF line endings"),
            "{}",
            error.redacted_message()
        );

        // The endings every current tool writes are unaffected, and both
        // rules agree on them.
        let crlf = "# T\r\n\r\nLead\r\ncontinued\r\n\r\n## End\r\n";
        assert_eq!(integer(crlf, "h1.0.paragraph.0.source_start_line"), 3);
        assert_eq!(integer(crlf, "h1.0.paragraph.0.source_end_line"), 4);
        assert_eq!(integer(crlf, "h1.0.h2.0.source_start_line"), 6);

        // No final newline still numbers its last line.
        let bare = "# T\n\nLead";
        assert_eq!(integer(bare, "h1.0.paragraph.0.source_end_line"), 3);
    }

    #[test]
    fn frontmatter_range_includes_both_delimiters() {
        let source = "---\ntitle: T\nnested:\n  token_secret: hidden\n---\n\n# T\n";
        assert_eq!(integer(source, "preamble.blocks.0.source_start_line"), 1);
        assert_eq!(integer(source, "preamble.blocks.0.source_end_line"), 5);
        assert_eq!(text(source, "preamble.blocks.0.text"), "");
    }

    #[test]
    fn thematic_break_is_a_block_with_no_text() {
        assert_eq!(
            shape("# T\n\na\n\n---\n\nb\n", "h1.0.blocks"),
            [
                ("paragraph".to_string(), "a".to_string()),
                ("rule".to_string(), String::new()),
                ("paragraph".to_string(), "b".to_string()),
            ]
        );
        // The paragraph view skips it, so "the second paragraph" stays the
        // second paragraph.
        assert_eq!(
            shape("# T\n\na\n\n---\n\nb\n", "h1.0.paragraph"),
            [
                ("paragraph".to_string(), "a".to_string()),
                ("paragraph".to_string(), "b".to_string()),
            ]
        );
    }

    #[test]
    fn a_byte_order_mark_makes_the_first_block_a_paragraph() {
        // CommonMark does not strip a BOM, so `\u{feff}# Title` is not a
        // heading. Pinned because a Windows editor writes one silently: the
        // file then has no section at all, which fails loudly — the outcome to
        // keep, against publishing "\u{feff}Title" as a name.
        assert_eq!(
            types("\u{feff}# Title\n\nlead\n", "preamble.blocks"),
            ["paragraph".to_string(), "paragraph".to_string()]
        );
    }

    #[test]
    fn empty_document_has_no_blocks() {
        assert_eq!(shape("", "preamble.blocks"), []);
        assert_eq!(shape("\n\n   \n", "preamble.blocks"), []);
    }

    #[test]
    fn code_block_keeps_its_lines_and_drops_one_trailing_newline() {
        assert_eq!(
            shape("```\nline one\nline two\n```\n", "preamble.blocks"),
            [("code".to_string(), "line one\nline two".to_string())]
        );
    }

    /// `text` flattens inline markup; `inlines` keeps exactly what that drops:
    /// which words are code, where a link points, what is an image.
    #[test]
    fn inlines_keep_what_text_flattens() {
        let source =
            "See [the **docs**](docs.md), ![alt *x*](img.png) and `code` <b>b</b>\\\nend\n";
        assert_eq!(
            text(source, "preamble.paragraph.0.text"),
            "See the docs, alt x and code b end"
        );
        let kinds = |path: &str| -> Vec<(String, String)> {
            at(source, path)
                .unwrap()
                .as_array()
                .unwrap()
                .iter()
                .map(|node| {
                    (
                        node.get("type")
                            .and_then(Value::as_str)
                            .unwrap()
                            .to_string(),
                        node.get("text")
                            .and_then(Value::as_str)
                            .unwrap()
                            .to_string(),
                    )
                })
                .collect()
        };
        let pairs = |items: &[(&str, &str)]| -> Vec<(String, String)> {
            items
                .iter()
                .map(|(kind, text)| (kind.to_string(), text.to_string()))
                .collect()
        };
        assert_eq!(
            kinds("preamble.paragraph.0.inlines"),
            pairs(&[
                ("text", "See "),
                ("link", "the docs"),
                ("text", ", "),
                ("image", "alt x"),
                ("text", " and "),
                ("code", "code"),
                ("text", " "),
                ("html", "<b>"),
                ("text", "b"),
                ("html", "</b>"),
                ("line_break", ""),
                ("text", "end"),
            ])
        );
        assert_eq!(
            kinds("preamble.paragraph.0.inlines.docs.inlines"),
            pairs(&[("text", "the "), ("strong", "docs")])
        );
        assert_eq!(
            text(source, "preamble.paragraph.0.inlines.docs.destination_url"),
            "docs.md"
        );
        assert_eq!(
            text(source, "preamble.paragraph.0.inlines.3.destination_url"),
            "img.png"
        );
        // Alt text is plain text when rendered, so an image has no children.
        assert!(
            at(source, "preamble.paragraph.0.inlines.3.inlines").is_err(),
            "an image reports flattened alt text only"
        );
    }

    #[test]
    fn a_heading_and_its_section_report_inlines() {
        let source = "# Run `serve` now\n";
        assert_eq!(text(source, "h1.0.text"), "Run serve now");
        assert_eq!(text(source, "h1.0.inlines.1.type"), "code");
        assert_eq!(text(source, "h1.0.inlines.1.text"), "serve");
    }

    /// A soft break is a wrapped line, which is presentation: it joins the
    /// surrounding text node rather than becoming a node of its own.
    #[test]
    fn a_soft_break_joins_adjacent_text() {
        assert_eq!(
            text("one\ntwo\n", "preamble.paragraph.0.inlines.0.text"),
            "one two"
        );
        assert!(at("one\ntwo\n", "preamble.paragraph.0.inlines.1").is_err());
    }

    /// A code fence inside a list item or a blockquote is still a `code`
    /// block: containers report their children, not only flattened text.
    #[test]
    fn containers_report_their_child_blocks() {
        let source = "- item\n\n  ```bash\n  nested\n  ```\n\n> ```json\n> {}\n> ```\n";
        assert_eq!(text(source, "preamble.blocks.0.blocks.0.type"), "item");
        assert_eq!(
            text(source, "preamble.blocks.0.blocks.0.blocks.1.type"),
            "code"
        );
        assert_eq!(
            text(source, "preamble.blocks.0.blocks.0.blocks.1.language"),
            "bash"
        );
        assert_eq!(
            text(source, "preamble.blocks.0.blocks.0.blocks.1.text"),
            "nested"
        );
        assert_eq!(
            integer(
                source,
                "preamble.blocks.0.blocks.0.blocks.1.source_start_line"
            ),
            3
        );
        assert_eq!(text(source, "preamble.blocks.1.blocks.0.type"), "code");
        assert_eq!(text(source, "preamble.blocks.1.blocks.0.language"), "json");
        assert_eq!(text(source, "preamble.blocks.1.blocks.0.text"), "{}");
        // The flattened view is unchanged.
        assert_eq!(text(source, "preamble.blocks.0.text"), "item\nnested");
    }

    /// The reported tree of the deepest file the reader accepts must still be
    /// readable as JSON, inside a protocol envelope, by a reader that stops at
    /// 128 levels — or `afdata get` emits documents it cannot read back.
    #[test]
    fn the_deepest_accepted_file_reports_a_tree_json_can_read_back() {
        fn depth(value: &Value) -> usize {
            match value {
                Value::Array(items) => 1 + items.iter().map(depth).max().unwrap_or(0),
                Value::Object(fields) => 1 + fields.values().map(depth).max().unwrap_or(0),
                _ => 0,
            }
        }
        let headings = "# a\n## b\n### c\n#### d\n##### e\n###### f\n";
        // A list item is two levels (list, item), the paragraph inside one more.
        let deepest = [
            format!("{headings}{}x\n", "> ".repeat(MAX_BLOCK_DEPTH - 1)),
            format!("{headings}{}x\n", "- ".repeat((MAX_BLOCK_DEPTH - 1) / 2)),
            format!("{headings}{}*x*\n", "> ".repeat(MAX_BLOCK_DEPTH - 3)),
        ];
        for source in deepest {
            let tree = load(&source).unwrap();
            assert!(depth(&tree) <= 112, "{} levels", depth(&tree));
            let json = serde_json::to_string(&tree).unwrap();
            let enveloped = format!("{{\"kind\":\"result\",\"result\":{{\"value\":{json}}}}}");
            serde_json::from_str::<serde_json::Value>(&enveloped).unwrap();
        }
    }

    #[test]
    fn inline_nesting_counts_toward_the_depth_limit() {
        let nested = |depth: usize| format!("{}x{}\n", "*".repeat(depth), "*".repeat(depth));
        assert!(load(&nested(8)).is_ok());
        let error = load(&nested(400)).unwrap_err();
        assert_eq!(error.code(), "document_source_refused");
    }
}