Skip to main content

agent_first_data/document/format/
markdown.rs

1//! Markdown mode: read a CommonMark file as a tree of heading sections.
2//! Read-only — Markdown prose is never written back.
3//!
4//! A heading owns everything under it until the next heading of its own level
5//! or shallower, so the document becomes a tree. Each section reports its
6//! heading `text` and `level`, its own `blocks` in source order, the
7//! `paragraph` subset of those, and its child sections under `h2`/`h3`/…
8//! Anything before the first heading is `preamble`, which carries the same
9//! `blocks`/`paragraph` pair.
10//!
11//! ```text
12//! preamble.blocks.0   → { type: "frontmatter", format: "toml", text: "" }
13//! preamble.paragraph.0 → { type: "paragraph", text: "CI" }       (a badge line)
14//! h1.0.text           → "Real"
15//! h1.0.paragraph.0    → { type: "paragraph", text: "The lead." }
16//! h1.0.blocks.1       → { type: "code", language: "bash", text: "…" }
17//! h1.0.h2.0.text      → "A quick look"
18//! ```
19//!
20//! Segments are matched by content as well as by index (see
21//! [`Format::array_rule`](crate::document::Format::array_rule)): `h2.look`
22//! finds the section headed "A quick look", and matching several sections is an
23//! error rather than a guess. That is what makes an address survive editing —
24//! `h2.3` moves the moment a section is inserted above it, and a top-level
25//! index moves the moment a badge line appears above the title.
26//!
27//! Sections are the reason the tree is not flat. A heading level is the one
28//! piece of hierarchy CommonMark states outright, and folding on it costs
29//! nothing while giving every address a stable frame: content is addressed
30//! relative to the heading it lives under, not to the top of the file.
31//!
32//! What this backend owns is the *specification* layer — block identification,
33//! block boundaries, and the heading nesting that follows from levels — and
34//! nothing above it. Where a document's title lives, whether the first
35//! paragraph is a synopsis, which blockquote carries a prompt: those are one
36//! project's layout conventions, and they stay with the caller that holds them.
37//! The distinction matters because block boundaries are precisely the part a
38//! hand-rolled line scanner gets wrong: setext headings, the seven HTML-block
39//! start conditions, four-space indented code, and the rule that an ATX heading
40//! interrupts a paragraph are each a rule a `^# ` regex does not have.
41//!
42//! Detection is never automatic: a `.md` path resolves to no format on its own
43//! and the caller must ask for `--input-format markdown`. The same file is
44//! legitimately readable as `yaml-frontmatter`, and a reader that guesses
45//! between two valid readings of one file is the shape-guessing AFDATA avoids.
46//!
47//! Deliberately out of scope, so that what this does return is exact:
48//!
49//! - **CommonMark with metadata blocks.** GFM tables, footnotes, task lists,
50//!   and strikethrough are disabled. A leading pair of matching column-zero
51//!   `+++` or `---` fence lines brackets metadata even when its first content
52//!   line is blank. The Markdown parser can also recognize metadata blocks
53//!   later in the document.
54//! - **No parsing or copying of frontmatter fields.** It is reported as one
55//!   block with `format: "toml"|"yaml"` and empty `text`;
56//!   `--input-format toml-frontmatter` is the reading that turns it into
57//!   values. Omitting the raw metadata also prevents this structural reading
58//!   from becoming a way around field-name-based secret redaction.
59//! - **`text` is flattened plain text.** Emphasis is unwrapped, a code span
60//!   keeps only its content, a link keeps its text, an image keeps its alt
61//!   text, and inline HTML tags are dropped. What was flattened away is kept
62//!   beside it: a paragraph, a heading, and a section report `inlines`, the
63//!   ordered inline tree (`text`, `code`, `html`, `line_break`, and `emphasis`,
64//!   `strong`, `link` with their own `inlines`; `link` and `image` carry
65//!   `destination_url`). A blockquote, a list, and a list item report their
66//!   child blocks under `blocks`, so a code fence inside a list item is still a
67//!   `code` block. (Heading sections nest by level, not by walking a block.)
68//! - **No byte offsets or columns.** Every block does carry 1-based inclusive
69//!   `source_start_line` / `source_end_line`. Every section carries its whole
70//!   source range plus `heading_end_line` for the
71//!   heading alone. These are enough to splice whole Markdown blocks without
72//!   making every consumer implement UTF-8 byte indexing.
73//! - **No Markdown-to-Markdown transformation.** Rewriting a document in place
74//!   needs source-preserving serialization, which is a separate design, not a
75//!   rider on a reader.
76
77use std::{collections::BTreeMap, ops::Range};
78
79use pulldown_cmark::{CodeBlockKind, Event, MetadataBlockKind, Options, Parser, Tag};
80
81use crate::document::{DocumentError, DocumentResult, Value};
82
83use super::frontmatter::{self, Delimiter};
84
85/// Parse `content` as CommonMark into the section tree described above.
86///
87/// CommonMark has no invalid-input production — every UTF-8 string is some
88/// sequence of blocks — so this fails only where afdata declines to answer: a
89/// bare carriage return, or block nesting more than 48 levels deep. An
90/// empty string yields an empty `preamble` and no sections.
91pub fn load(content: &str) -> DocumentResult<Value> {
92    reject_lone_carriage_return(content)?;
93    let lines = LineIndex::new(content);
94    let mut blocks = Vec::new();
95    let mut markdown = Parser::new_ext(content, metadata_options())
96        .into_offset_iter()
97        .peekable();
98    let mut offset = 0;
99    if let Some((delimiter, parts)) = frontmatter::leading(content) {
100        let closing_line = parts.post.split_inclusive('\n').next().unwrap_or("");
101        let metadata_end = parts.pre.len() + parts.frontmatter.len() + closing_line.len();
102        // The Markdown extension may close YAML earlier with `...`. Retain
103        // that reading to preserve the subsequent body. Reparse only when
104        // the extension missed the shared fence or read past it.
105        if !matches!(
106            markdown.peek(),
107            Some((Event::Start(Tag::MetadataBlock(_)), range))
108                if range.start == 0 && range.end <= metadata_end
109        ) {
110            offset = metadata_end;
111            let format = match delimiter {
112                Delimiter::Plus => "toml",
113                Delimiter::Dash => "yaml",
114            };
115            blocks.push(metadata_block(format, &(0..offset), &lines));
116            markdown = Parser::new_ext(&content[offset..], metadata_options())
117                .into_offset_iter()
118                .peekable();
119        }
120    }
121    let events: Vec<SpannedEvent<'_>> = markdown
122        .map(|(event, range)| (event, range.start + offset..range.end + offset))
123        .collect();
124    reject_deep_nesting(&events)?;
125    let mut cursor = 0;
126    blocks.extend(read_blocks(&events, &lines, &mut cursor));
127    Ok(fold_sections(blocks))
128}
129
130type SpannedEvent<'a> = (Event<'a>, Range<usize>);
131
132/// Byte offsets of logical line starts, used only inside the parser boundary.
133///
134/// Public consumers see line numbers, not byte offsets. LF and CRLF input use
135/// the same `\n`-based numbering as common line-oriented tools; a lone CR is
136/// rejected before this index is constructed.
137struct LineIndex<'a> {
138    content: &'a str,
139    starts: Vec<usize>,
140}
141
142impl<'a> LineIndex<'a> {
143    /// Index the line starts of `content`, counting a line as everything up to
144    /// the next `\n`.
145    ///
146    /// Not CommonMark's rule, deliberately. CommonMark also treats a bare `\r`
147    /// as a line ending, and these numbers exist to be handed to something
148    /// else — `sed -n '5,10p'`, `head -n`, an editor jump, a `git diff` — all
149    /// of which split on `\n` alone. A number that only afdata can interpret
150    /// is worse than no number: it looks usable and silently points one line
151    /// off. CRLF agrees with both rules, so the two definitions differ only
152    /// for a bare `\r`, which [`reject_lone_carriage_return`] refuses outright
153    /// rather than reporting a line number nothing else can act on.
154    fn new(content: &'a str) -> Self {
155        let mut starts = vec![0];
156        for (offset, byte) in content.bytes().enumerate() {
157            if byte == b'\n' {
158                starts.push(offset + 1);
159            }
160        }
161        Self { content, starts }
162    }
163
164    fn number_at(&self, offset: usize) -> i64 {
165        let line = self.starts.partition_point(|start| *start <= offset);
166        i64::try_from(line).unwrap_or(i64::MAX)
167    }
168
169    /// The 1-based inclusive line range a source span covers.
170    ///
171    /// The span's trailing whitespace is dropped first. Most block kinds end
172    /// at their own last character, but pulldown-cmark runs a list's span on
173    /// to where the next block begins, so it carries the blank lines that
174    /// separate them. A range is a splice instruction — a consumer cutting one
175    /// out must not take the separator with it, or the blocks on either side
176    /// merge (a lead paragraph absorbed into the setext heading below it).
177    fn range(&self, source: &Range<usize>) -> SourceLines {
178        let content_end = self
179            .content
180            .get(..source.end)
181            .map_or(source.end, |head| head.trim_end().len())
182            .max(source.start);
183        let end_offset = content_end.saturating_sub(1).max(source.start);
184        SourceLines {
185            start: self.number_at(source.start),
186            end: self.number_at(end_offset),
187        }
188    }
189}
190
191#[derive(Clone, Copy)]
192struct SourceLines {
193    start: i64,
194    end: i64,
195}
196
197/// Refuse a document containing a bare `\r` — a carriage return not followed
198/// by a newline.
199///
200/// This is the single case where CommonMark's line rule and every other tool's
201/// disagree: CommonMark ends a line there, `sed`/`awk`/`wc`/`head`/`git` do
202/// not. A reported line number is only useful if the thing the caller hands it
203/// to counts the same way, and for such a file no single number can satisfy
204/// both — two blocks would share one line, and a splice by that number would
205/// cut the wrong text with nothing to notice it by.
206///
207/// So the file is refused instead of answered wrongly. It is the classic Mac
208/// (pre-2002) line ending; CRLF and LF, which every current tool produces, are
209/// unaffected because both rules agree on them.
210fn reject_lone_carriage_return(content: &str) -> DocumentResult<()> {
211    let bytes = content.as_bytes();
212    for (offset, byte) in bytes.iter().enumerate() {
213        if *byte == b'\r' && bytes.get(offset + 1) != Some(&b'\n') {
214            return Err(DocumentError::SourceRefused {
215                format: "Markdown".to_string(),
216                detail: format!(
217                    "a bare carriage return at byte {offset} ends a line for CommonMark but not \
218                     for the tools these line numbers are meant to feed; convert the file to LF \
219                     or CRLF line endings"
220                ),
221            });
222        }
223    }
224    Ok(())
225}
226
227/// How deep blocks and inline spans may nest. The walk recurses once per
228/// level, and the reported tree is deeper still: each level becomes an object
229/// plus the array of its children, and the root and six heading levels add
230/// about fifteen more. 48 keeps the deepest accepted file's tree near 111
231/// levels, so it fits inside the 128 a JSON reader allows — serde_json's
232/// limit, which `afdata get` applies to its own output read back — with room
233/// for an envelope around it.
234const MAX_BLOCK_DEPTH: usize = 48;
235
236/// Refuse nesting the recursive walk cannot hold before it starts, so a file
237/// of `> > > …` is an error rather than a stack overflow. Inline spans count
238/// too: the reported inline tree nests exactly as deep as they do.
239fn reject_deep_nesting(events: &[SpannedEvent<'_>]) -> DocumentResult<()> {
240    let mut depth = 0usize;
241    for (event, _) in events {
242        match event {
243            Event::Start(_) => {
244                depth += 1;
245                if depth > MAX_BLOCK_DEPTH {
246                    return Err(DocumentError::SourceRefused {
247                        format: "Markdown".to_string(),
248                        detail: format!(
249                            "blocks and inline spans nest deeper than {MAX_BLOCK_DEPTH} levels"
250                        ),
251                    });
252                }
253            }
254            Event::End(_) => depth = depth.saturating_sub(1),
255            _ => {}
256        }
257    }
258    Ok(())
259}
260
261/// Keep suppressing metadata the Markdown parser recognizes, such as YAML
262/// metadata closed by `...`. Treating it as prose could expose fields that
263/// previous versions omitted.
264fn metadata_options() -> Options {
265    Options::ENABLE_YAML_STYLE_METADATA_BLOCKS | Options::ENABLE_PLUSES_DELIMITED_METADATA_BLOCKS
266}
267
268fn metadata_block(format: &str, source: &Range<usize>, lines: &LineIndex<'_>) -> Value {
269    block(
270        "frontmatter",
271        String::new(),
272        source,
273        lines,
274        vec![("format", Value::String(format.to_string()))],
275    )
276}
277
278/// One heading and everything it owns, while the tree is still being built.
279struct Section {
280    level: i64,
281    text: String,
282    inlines: Value,
283    heading_lines: SourceLines,
284    blocks: Vec<Value>,
285    children: Vec<Section>,
286}
287
288/// Fold a flat block sequence into the section tree.
289///
290/// A heading closes every open section at its own level or deeper, then opens
291/// its own — the standard reading of heading levels, and the only hierarchy
292/// CommonMark itself states. A level may be skipped (an `h3` directly under an
293/// `h1`); the `h3` simply becomes a child of whatever section is open, since
294/// there is no `h2` to hold it.
295fn fold_sections(blocks: Vec<Value>) -> Value {
296    let mut preamble = Vec::new();
297    let mut roots: Vec<Section> = Vec::new();
298    let mut open: Vec<Section> = Vec::new();
299
300    for block in blocks {
301        let heading_level = (block.get("type").and_then(Value::as_str) == Some("heading"))
302            .then(|| block.get("level").and_then(Value::as_integer))
303            .flatten();
304        match heading_level {
305            Some(level) => {
306                while open.last().is_some_and(|section| section.level >= level) {
307                    close_section(&mut open, &mut roots);
308                }
309                open.push(Section {
310                    level,
311                    text: block
312                        .get("text")
313                        .and_then(Value::as_str)
314                        .unwrap_or_default()
315                        .to_string(),
316                    inlines: block
317                        .get("inlines")
318                        .cloned()
319                        .unwrap_or_else(|| Value::Array(Vec::new())),
320                    heading_lines: SourceLines {
321                        start: block
322                            .get("source_start_line")
323                            .and_then(Value::as_integer)
324                            .unwrap_or_default(),
325                        end: block
326                            .get("source_end_line")
327                            .and_then(Value::as_integer)
328                            .unwrap_or_default(),
329                    },
330                    blocks: Vec::new(),
331                    children: Vec::new(),
332                });
333            }
334            // Content before the first heading belongs to no section. It is
335            // kept rather than dropped: "this file opens with a generated-file
336            // comment" is a fact, and whether that is acceptable is the
337            // caller's rule to apply, not this reader's to enforce by omission.
338            None => match open.last_mut() {
339                Some(section) => section.blocks.push(block),
340                None => preamble.push(block),
341            },
342        }
343    }
344    while !open.is_empty() {
345        close_section(&mut open, &mut roots);
346    }
347
348    // `preamble` carries the same two views a section does, so "the first
349    // paragraph" is one address in both. As a bare array it was not: a `+++`
350    // block or a badge line above the prose shifted every index, which is the
351    // problem sections exist to remove.
352    let mut root = BTreeMap::from([("preamble".to_string(), Value::Object(block_views(preamble)))]);
353    insert_sections(&mut root, roots);
354    Value::Object(root)
355}
356
357/// Pop the deepest open section and file it under its parent, or under the
358/// document root when it has none.
359fn close_section(open: &mut Vec<Section>, roots: &mut Vec<Section>) {
360    let Some(done) = open.pop() else { return };
361    match open.last_mut() {
362        Some(parent) => parent.children.push(done),
363        None => roots.push(done),
364    }
365}
366
367/// File `sections` into `target` under `h1`/`h2`/… by their own level, each
368/// group in source order.
369fn insert_sections(target: &mut BTreeMap<String, Value>, sections: Vec<Section>) {
370    for section in sections {
371        let key = format!("h{}", section.level);
372        let group = target
373            .entry(key)
374            .or_insert_with(|| Value::Array(Vec::new()));
375        if let Some(items) = group.as_array_mut() {
376            items.push(section.into_value());
377        }
378    }
379}
380
381/// The two views every block container reports: `blocks` in source order, and
382/// the `paragraph` subset of them.
383///
384/// The subset is duplicated out of `blocks` on purpose. Prose is what a
385/// container is usually read for, and "the first paragraph" must not shift
386/// because a frontmatter block, a code fence, or a thematic break happened to
387/// land above it. Badge syntax and a GFM-looking pipe table are paragraphs
388/// under the deliberately enabled CommonMark grammar, so they remain in this
389/// view. `blocks` stays the one place that shows what the container actually
390/// looks like, in order.
391fn block_views(blocks: Vec<Value>) -> BTreeMap<String, Value> {
392    let of_kind = |kind: &str| {
393        Value::Array(
394            blocks
395                .iter()
396                .filter(|block| block.get("type").and_then(Value::as_str) == Some(kind))
397                .cloned()
398                .collect::<Vec<Value>>(),
399        )
400    };
401    let paragraph = of_kind("paragraph");
402    let blockquote = of_kind("blockquote");
403    BTreeMap::from([
404        ("paragraph".to_string(), paragraph),
405        ("blockquote".to_string(), blockquote),
406        ("blocks".to_string(), Value::Array(blocks)),
407    ])
408}
409
410impl Section {
411    fn into_value(self) -> Value {
412        let source_end_line = self.source_end_line();
413        let mut fields = block_views(self.blocks);
414        fields.insert("level".to_string(), Value::Integer(self.level));
415        fields.insert("text".to_string(), Value::String(self.text));
416        fields.insert("inlines".to_string(), self.inlines);
417        fields.insert(
418            "source_start_line".to_string(),
419            Value::Integer(self.heading_lines.start),
420        );
421        fields.insert(
422            "source_end_line".to_string(),
423            Value::Integer(source_end_line),
424        );
425        fields.insert(
426            "heading_end_line".to_string(),
427            Value::Integer(self.heading_lines.end),
428        );
429        insert_sections(&mut fields, self.children);
430        Value::Object(fields)
431    }
432
433    fn source_end_line(&self) -> i64 {
434        self.blocks
435            .iter()
436            .filter_map(|block| block.get("source_end_line"))
437            .filter_map(Value::as_integer)
438            .chain(self.children.iter().map(Section::source_end_line))
439            .max()
440            .unwrap_or(self.heading_lines.end)
441    }
442}
443
444/// Read sibling blocks until the enclosing container's `End` event, or the end
445/// of the stream at top level. Leaves `cursor` *on* that `End`, for the caller
446/// that opened the container to consume.
447fn read_blocks(
448    events: &[SpannedEvent<'_>],
449    lines: &LineIndex<'_>,
450    cursor: &mut usize,
451) -> Vec<Value> {
452    let mut blocks = Vec::new();
453    while let Some((event, source)) = events.get(*cursor) {
454        match event {
455            Event::End(_) => break,
456            Event::Rule => {
457                let source = source.clone();
458                *cursor += 1;
459                blocks.push(block("rule", String::new(), &source, lines, vec![]));
460            }
461            Event::Start(tag) if !is_inline_tag(tag) => {
462                let source = source.clone();
463                *cursor += 1;
464                blocks.extend(read_block(tag, &source, events, lines, cursor));
465            }
466            // Inline content standing where a block belongs: a tight list's
467            // item holds its text directly, with no paragraph around it.
468            // Reading it as an implicit paragraph is what makes a tight and a
469            // loose list report the same items.
470            _ => {
471                let first = *cursor;
472                let (text, inlines) = read_loose_inline(events, cursor);
473                if !text.is_empty() {
474                    let source = covered_range(events, first, *cursor);
475                    blocks.push(block(
476                        "paragraph",
477                        text,
478                        &source,
479                        lines,
480                        vec![("inlines", inlines)],
481                    ));
482                }
483            }
484        }
485    }
486    blocks
487}
488
489/// Whether `tag` wraps text inside a block rather than opening one.
490fn is_inline_tag(tag: &Tag<'_>) -> bool {
491    matches!(
492        tag,
493        Tag::Emphasis
494            | Tag::Strong
495            | Tag::Strikethrough
496            | Tag::Superscript
497            | Tag::Subscript
498            | Tag::Link { .. }
499            | Tag::Image { .. }
500    )
501}
502
503/// Read the one block opened by `tag`, consuming through its own `End`.
504fn read_block(
505    tag: &Tag<'_>,
506    source: &Range<usize>,
507    events: &[SpannedEvent<'_>],
508    lines: &LineIndex<'_>,
509    cursor: &mut usize,
510) -> Option<Value> {
511    match tag {
512        Tag::Paragraph => {
513            let (text, inlines) = read_inline(events, cursor);
514            Some(block(
515                "paragraph",
516                text,
517                source,
518                lines,
519                vec![("inlines", inlines)],
520            ))
521        }
522        Tag::Heading { level, .. } => {
523            let (text, inlines) = read_inline(events, cursor);
524            Some(block(
525                "heading",
526                text,
527                source,
528                lines,
529                vec![
530                    ("level", Value::Integer(*level as i64)),
531                    ("inlines", inlines),
532                ],
533            ))
534        }
535        Tag::CodeBlock(kind) => {
536            // CommonMark's info string is everything after the opening fence;
537            // in practice it is the language. An indented block has none.
538            let info = match kind {
539                CodeBlockKind::Fenced(info) => info.trim().to_string(),
540                CodeBlockKind::Indented => String::new(),
541            };
542            Some(block(
543                "code",
544                read_verbatim(events, cursor),
545                source,
546                lines,
547                // `language`, not CommonMark's `info`: a field must say what
548                // it holds without its neighbours (spec/agent-first-data.md
549                // rule 5, "Self-contained"). Sharing one name with the
550                // frontmatter block below made `info: "toml"` mean either a
551                // fence written in TOML or a `+++` delimiter, tellable apart
552                // only by also reading `type`.
553                vec![("language", Value::String(info))],
554            ))
555        }
556        Tag::HtmlBlock => Some(block(
557            "html",
558            read_verbatim(events, cursor),
559            source,
560            lines,
561            vec![],
562        )),
563        // A `+++`/`---` metadata block, reported as its own kind without
564        // copying its potentially secret-bearing source into `text`: which
565        // fields it holds is TOML's or YAML's answer, and
566        // `--input-format toml-frontmatter` is the reading that gives it.
567        // `format` names the delimiter's dialect, matching the
568        // `--input-format` token that reads its fields.
569        Tag::MetadataBlock(kind) => {
570            // Advance without collecting the metadata into a second String.
571            // The source parser already borrows it, and this view deliberately
572            // exposes neither a copy nor a flattened form.
573            skip_subtree(events, cursor);
574            let format = match kind {
575                MetadataBlockKind::PlusesStyle => "toml",
576                MetadataBlockKind::YamlStyle => "yaml",
577            };
578            Some(metadata_block(format, source, lines))
579        }
580        Tag::BlockQuote(_) => {
581            let (text, children) = read_container(events, lines, cursor);
582            Some(block(
583                "blockquote",
584                text,
585                source,
586                lines,
587                vec![("blocks", children)],
588            ))
589        }
590        Tag::List(first_number) => {
591            let (text, children) = read_container(events, lines, cursor);
592            Some(block(
593                "list",
594                text,
595                source,
596                lines,
597                vec![
598                    ("ordered", Value::Bool(first_number.is_some())),
599                    ("blocks", children),
600                ],
601            ))
602        }
603        // An item exists only as a list's child: it is reached through the
604        // list's `blocks`, one `item` per list item, each with its own blocks.
605        Tag::Item => {
606            let (text, children) = read_container(events, lines, cursor);
607            Some(block(
608                "item",
609                text,
610                source,
611                lines,
612                vec![("blocks", children)],
613            ))
614        }
615        // Tables, footnote definitions, and definition lists require options
616        // this backend does not enable. Skip unknown subtrees if the option
617        // set ever widens.
618        _ => {
619            skip_subtree(events, cursor);
620            None
621        }
622    }
623}
624
625/// Flattened text of a container block — its child blocks' `text` joined by a
626/// newline — and the child blocks themselves, consuming through the
627/// container's own `End`.
628///
629/// Block boundaries survive as newlines because they are structure; a wrapped
630/// line inside one paragraph does not, because it is presentation (see
631/// [`read_inline`]). Children that flatten to nothing, such as a thematic
632/// break, contribute nothing rather than a blank line.
633fn read_container(
634    events: &[SpannedEvent<'_>],
635    lines: &LineIndex<'_>,
636    cursor: &mut usize,
637) -> (String, Value) {
638    let children = read_blocks(events, lines, cursor);
639    // `read_blocks` stops on the container's `End` rather than past it.
640    *cursor += 1;
641    let text = children
642        .iter()
643        .filter_map(|child| child.get("text").and_then(Value::as_str))
644        .filter(|text| !text.is_empty())
645        .collect::<Vec<_>>()
646        .join("\n");
647    (text, Value::Array(children))
648}
649
650/// Flattened plain text of a leaf block's inline content, and the inline tree
651/// it was flattened from, consuming through that block's own `End`.
652///
653/// In `text`, emphasis and strong are unwrapped, a code span keeps its
654/// content, a link keeps its text and drops its URL, an image keeps its alt
655/// text, raw inline HTML tags are dropped, and every line break inside the
656/// block — soft or hard — becomes a single space. The result is one line of
657/// plain prose, which is what a name, a synopsis, or a prompt is. The tree
658/// keeps what that dropped; see [`InlineReader`].
659fn read_inline(events: &[SpannedEvent<'_>], cursor: &mut usize) -> (String, Value) {
660    let read = read_loose_inline(events, cursor);
661    if matches!(events.get(*cursor), Some((Event::End(_), _))) {
662        *cursor += 1;
663    }
664    read
665}
666
667/// [`read_inline`] without an owning block: stops *before* the next block
668/// boundary instead of consuming a closing `End`. This is the form a tight
669/// list item needs, whose text has no paragraph of its own to end.
670fn read_loose_inline(events: &[SpannedEvent<'_>], cursor: &mut usize) -> (String, Value) {
671    let mut reader = InlineReader::default();
672    let mut depth = 0usize;
673    while let Some((event, _)) = events.get(*cursor) {
674        match event {
675            Event::Start(tag) if depth == 0 && !is_inline_tag(tag) => break,
676            Event::End(_) if depth == 0 => break,
677            Event::Rule if depth == 0 => break,
678            Event::Start(tag) => {
679                depth += 1;
680                reader.open(tag);
681            }
682            Event::End(_) => {
683                depth -= 1;
684                reader.close();
685            }
686            Event::Text(chunk) => reader.text(chunk),
687            Event::Code(chunk) => reader.leaf("code", chunk, chunk),
688            Event::InlineHtml(chunk) | Event::Html(chunk) => reader.leaf("html", chunk, ""),
689            Event::SoftBreak => reader.text(" "),
690            Event::HardBreak => reader.leaf("line_break", "", " "),
691            _ => {}
692        }
693        *cursor += 1;
694    }
695    reader.finish()
696}
697
698/// One inline node while its parent is still open.
699struct Inline {
700    kind: &'static str,
701    /// Flattened text, under the same rule as the block's `text`.
702    text: String,
703    destination_url: Option<String>,
704    /// `None` for a leaf, and for an image: alt text is plain text in the
705    /// rendered output, so its markup is not reported as structure.
706    children: Option<Vec<Inline>>,
707}
708
709impl Inline {
710    fn into_value(self) -> Value {
711        // A span's flattened text is trimmed like a block's; a leaf is not, or
712        // the space between `see ` and a following link would be lost.
713        let text = if self.children.is_some() || self.destination_url.is_some() {
714            self.text.trim().to_string()
715        } else {
716            self.text
717        };
718        let mut fields = BTreeMap::from([
719            ("type".to_string(), Value::String(self.kind.to_string())),
720            ("text".to_string(), Value::String(text)),
721        ]);
722        if let Some(url) = self.destination_url {
723            fields.insert("destination_url".to_string(), Value::String(url));
724        }
725        if let Some(children) = self.children {
726            fields.insert("inlines".to_string(), inline_values(children));
727        }
728        Value::Object(fields)
729    }
730}
731
732fn inline_values(inlines: Vec<Inline>) -> Value {
733    Value::Array(inlines.into_iter().map(Inline::into_value).collect())
734}
735
736/// Builds a block's flattened `text` and its inline tree in one pass.
737///
738/// Every open span accumulates its own flattened text as content arrives, so
739/// a link reports the text a reader sees without the caller walking its
740/// children. Adjacent text — including a soft break, which is presentation —
741/// merges into one `text` node. Spans that need a dialect this reader does not
742/// enable (strikethrough, sub- and superscript) cannot occur; if one did, its
743/// content would join its parent rather than invent a node kind.
744#[derive(Default)]
745struct InlineReader {
746    text: String,
747    roots: Vec<Inline>,
748    open: Vec<Inline>,
749    /// Per opened tag, whether it opened a node in `open`.
750    opened: Vec<bool>,
751}
752
753impl InlineReader {
754    /// The list new content joins. Never an image's: content inside one is
755    /// only flattened (see `in_image`), so an image is never open here.
756    fn siblings(&mut self) -> &mut Vec<Inline> {
757        match self.open.last_mut() {
758            Some(span) => span.children.get_or_insert_with(Vec::new),
759            None => &mut self.roots,
760        }
761    }
762
763    fn flatten(&mut self, chunk: &str) {
764        self.text.push_str(chunk);
765        for span in &mut self.open {
766            span.text.push_str(chunk);
767        }
768    }
769
770    fn in_image(&self) -> bool {
771        self.open.iter().any(|span| span.kind == "image")
772    }
773
774    fn text(&mut self, chunk: &str) {
775        self.flatten(chunk);
776        if self.in_image() {
777            return;
778        }
779        let siblings = self.siblings();
780        match siblings.last_mut() {
781            Some(last) if last.kind == "text" => last.text.push_str(chunk),
782            _ => siblings.push(Inline {
783                kind: "text",
784                text: chunk.to_string(),
785                destination_url: None,
786                children: None,
787            }),
788        }
789    }
790
791    fn leaf(&mut self, kind: &'static str, node_text: &str, flat: &str) {
792        self.flatten(flat);
793        if self.in_image() {
794            return;
795        }
796        self.siblings().push(Inline {
797            kind,
798            text: node_text.to_string(),
799            destination_url: None,
800            children: None,
801        });
802    }
803
804    fn open(&mut self, tag: &Tag<'_>) {
805        let span = match tag {
806            Tag::Emphasis => Some(("emphasis", None, true)),
807            Tag::Strong => Some(("strong", None, true)),
808            Tag::Link { dest_url, .. } => Some(("link", Some(dest_url.to_string()), true)),
809            Tag::Image { dest_url, .. } => Some(("image", Some(dest_url.to_string()), false)),
810            _ => None,
811        };
812        // Inside an image everything is alt text: no nested nodes.
813        let span = span.filter(|_| !self.in_image());
814        self.opened.push(span.is_some());
815        if let Some((kind, destination_url, structured)) = span {
816            self.open.push(Inline {
817                kind,
818                text: String::new(),
819                destination_url,
820                children: structured.then(Vec::new),
821            });
822        }
823    }
824
825    fn close(&mut self) {
826        if self.opened.pop() == Some(true)
827            && let Some(done) = self.open.pop()
828        {
829            self.siblings().push(done);
830        }
831    }
832
833    fn finish(mut self) -> (String, Value) {
834        while !self.open.is_empty() {
835            self.opened.push(true);
836            self.close();
837        }
838        (self.text.trim().to_string(), inline_values(self.roots))
839    }
840}
841
842/// Literal content of a code or HTML block, consuming through its `End`.
843///
844/// Nothing is flattened here — the content is not prose. The single trailing
845/// newline every such block carries (the line break before its closing fence,
846/// or ending its last line) is dropped; everything else is verbatim.
847fn read_verbatim(events: &[SpannedEvent<'_>], cursor: &mut usize) -> String {
848    let mut text = String::new();
849    while let Some((event, _)) = events.get(*cursor) {
850        *cursor += 1;
851        match event {
852            Event::End(_) => break,
853            Event::Text(chunk) | Event::Html(chunk) => text.push_str(chunk),
854            _ => {}
855        }
856    }
857    let unterminated = text.trim_suffix('\n');
858    unterminated.trim_suffix('\r').to_string()
859}
860
861/// Consume an unhandled container's whole subtree, including its own `End`.
862fn skip_subtree(events: &[SpannedEvent<'_>], cursor: &mut usize) {
863    let mut depth = 0usize;
864    while let Some((event, _)) = events.get(*cursor) {
865        *cursor += 1;
866        match event {
867            Event::Start(_) => depth += 1,
868            Event::End(_) => {
869                if depth == 0 {
870                    break;
871                }
872                depth -= 1;
873            }
874            _ => {}
875        }
876    }
877}
878
879/// The smallest source range covering events in `start..end`.
880///
881/// Top-level CommonMark blocks carry their full range on the opening event.
882/// This fallback exists for inline text in tight containers, where there is no
883/// paragraph `Start` event to lend us one.
884fn covered_range(events: &[SpannedEvent<'_>], start: usize, end: usize) -> Range<usize> {
885    let mut covered = events
886        .get(start)
887        .map(|(_, source)| source.clone())
888        .unwrap_or(0..0);
889    for (_, source) in events.get(start..end).unwrap_or_default() {
890        covered.start = covered.start.min(source.start);
891        covered.end = covered.end.max(source.end);
892    }
893    covered
894}
895
896/// Assemble one block: the `type`, flattened `text`, and 1-based inclusive
897/// source-line range every block carries, plus kind-specific fields.
898fn block(
899    kind: &str,
900    text: String,
901    source: &Range<usize>,
902    lines: &LineIndex<'_>,
903    extra: Vec<(&str, Value)>,
904) -> Value {
905    let source = lines.range(source);
906    let mut fields = BTreeMap::from([
907        ("type".to_string(), Value::String(kind.to_string())),
908        ("text".to_string(), Value::String(text)),
909        (
910            "source_start_line".to_string(),
911            Value::Integer(source.start),
912        ),
913        ("source_end_line".to_string(), Value::Integer(source.end)),
914    ]);
915    for (name, value) in extra {
916        fields.insert(name.to_string(), value);
917    }
918    Value::Object(fields)
919}
920
921#[cfg(test)]
922mod tests {
923    #![allow(clippy::unwrap_used, clippy::panic, clippy::expect_used)]
924    use super::*;
925    use crate::document::{Addressing, Format, get_path};
926
927    /// Read one address exactly as a caller would, through the same traversal
928    /// and the same format rule the CLI uses.
929    fn at(source: &str, path: &str) -> DocumentResult<Value> {
930        get_path(
931            &load(source).unwrap(),
932            path,
933            Addressing::INDEX_ONLY.with_array_rule(Format::Markdown.array_rule()),
934        )
935    }
936
937    fn text(source: &str, path: &str) -> String {
938        at(source, path)
939            .unwrap_or_else(|error| panic!("{path}: {error}"))
940            .as_str()
941            .unwrap_or_else(|| panic!("{path} is not a string"))
942            .to_string()
943    }
944
945    fn integer(source: &str, path: &str) -> i64 {
946        at(source, path)
947            .unwrap_or_else(|error| panic!("{path}: {error}"))
948            .as_integer()
949            .unwrap_or_else(|| panic!("{path} is not an integer"))
950    }
951
952    /// `(type, text)` of a block array, which is what a caller reads.
953    fn shape(source: &str, path: &str) -> Vec<(String, String)> {
954        at(source, path)
955            .unwrap_or_else(|error| panic!("{path}: {error}"))
956            .as_array()
957            .unwrap_or_else(|| panic!("{path} is not an array"))
958            .iter()
959            .map(|block| {
960                let field = |name: &str| {
961                    block
962                        .get(name)
963                        .and_then(Value::as_str)
964                        .unwrap_or_default()
965                        .to_string()
966                };
967                (field("type"), field("text"))
968            })
969            .collect()
970    }
971
972    fn types(source: &str, path: &str) -> Vec<String> {
973        shape(source, path).into_iter().map(|(k, _)| k).collect()
974    }
975
976    // ---- the eight probes -------------------------------------------------
977    //
978    // These are the cases a hand-rolled line scanner answered wrong — all eight
979    // of them. Each names the CommonMark rule it turns on, and each is the
980    // classification a caller's layout policy then reads.
981
982    #[test]
983    fn probe_1_setext_heading_is_a_heading() {
984        // An underlined title is a heading; `^# ` never sees it.
985        let source = "Title\n=====\n\nThe lead.\n";
986        assert_eq!(text(source, "h1.0.text"), "Title");
987        assert_eq!(text(source, "h1.0.paragraph.0.text"), "The lead.");
988    }
989
990    #[test]
991    fn probe_2_html_comment_before_the_heading_is_its_own_block() {
992        // A generated-file banner is an HTML block. It lands in `preamble`,
993        // where a caller can see it, and does not shift the title.
994        let source = "<!-- generated -->\n\n# Real\n\nThe lead.\n";
995        assert_eq!(
996            shape(source, "preamble.blocks"),
997            [("html".to_string(), "<!-- generated -->".to_string())]
998        );
999        assert_eq!(text(source, "h1.0.text"), "Real");
1000    }
1001
1002    #[test]
1003    fn probe_3_badge_line_before_the_heading_is_a_paragraph() {
1004        // The most common README opening there is. A flat reading would make
1005        // this block 0 and publish `CI` as the project's name; here it is
1006        // preamble and the title is still `h1.0`.
1007        let source = "[![CI](a.svg)](b)\n\n# Real\n\nThe lead.\n";
1008        assert_eq!(
1009            shape(source, "preamble.blocks"),
1010            [("paragraph".to_string(), "CI".to_string())]
1011        );
1012        assert_eq!(text(source, "h1.0.text"), "Real");
1013        assert_eq!(text(source, "h1.0.paragraph.0.text"), "The lead.");
1014    }
1015
1016    #[test]
1017    fn probe_4_fenced_code_in_the_lead_position_is_code() {
1018        // The section's first *block* is code, so `paragraph` is empty — a
1019        // caller asking for a synopsis gets a failure, not the code.
1020        let source = "# Real\n\n```bash\nafdata get x\n```\n";
1021        assert_eq!(
1022            shape(source, "h1.0.blocks"),
1023            [("code".to_string(), "afdata get x".to_string())]
1024        );
1025        assert_eq!(shape(source, "h1.0.paragraph"), []);
1026        assert_eq!(
1027            at(source, "h1.0.paragraph.0").unwrap_err().code(),
1028            "document_path_not_found"
1029        );
1030        assert_eq!(
1031            at(source, "h1.0.blocks.0.language").unwrap(),
1032            Value::String("bash".to_string())
1033        );
1034    }
1035
1036    #[test]
1037    fn probe_5_leading_fence_swallows_the_heading_inside_it() {
1038        // `# Real` is code here, not a heading — so there is no section at all
1039        // and the whole file is preamble.
1040        let source = "```\n# Real\n```\n";
1041        assert_eq!(
1042            shape(source, "preamble.blocks"),
1043            [("code".to_string(), "# Real".to_string())]
1044        );
1045        assert_eq!(
1046            at(source, "h1.0").unwrap_err().code(),
1047            "document_path_not_found"
1048        );
1049    }
1050
1051    #[test]
1052    fn probe_6_atx_heading_interrupts_a_paragraph() {
1053        // The rule that looks backwards and is not: a `# ` line ends the
1054        // paragraph it appears in rather than joining it. It also opens a
1055        // sibling section, so the lead stops there too.
1056        let source = "# Real\n\nThe lead.\n# looks like heading\nmore.\n";
1057        assert_eq!(text(source, "h1.0.text"), "Real");
1058        assert_eq!(
1059            shape(source, "h1.0.paragraph"),
1060            [("paragraph".to_string(), "The lead.".to_string())]
1061        );
1062        assert_eq!(text(source, "h1.1.text"), "looks like heading");
1063        assert_eq!(text(source, "h1.1.paragraph.0.text"), "more.");
1064    }
1065
1066    #[test]
1067    fn probe_7_four_space_indent_is_code_not_a_heading() {
1068        // The worst of the eight: an indented `# Title` reads as a title to a
1069        // scanner that strips leading whitespace, and is code to CommonMark.
1070        let source = "    # Indented\n\nAfter.\n";
1071        assert_eq!(
1072            types(source, "preamble.blocks"),
1073            ["code".to_string(), "paragraph".to_string()]
1074        );
1075        assert_eq!(
1076            at(source, "h1.0").unwrap_err().code(),
1077            "document_path_not_found"
1078        );
1079    }
1080
1081    #[test]
1082    fn probe_8_whole_paragraph_emphasis_is_unwrapped() {
1083        // Flattening gives this for free; a scanner needs a special case for
1084        // it, and still leaks the inner markers of the partial-emphasis form.
1085        assert_eq!(
1086            text("# Real\n\n**A bold tagline.**\n", "h1.0.paragraph.0.text"),
1087            "A bold tagline."
1088        );
1089        // Partial emphasis, a code span, and a link all flatten to plain text
1090        // too — the scanner leaked every one of these into published metadata.
1091        assert_eq!(
1092            text(
1093                "# T\n\nA **bold** `span` and a [link](https://example.com).\n",
1094                "h1.0.paragraph.0.text"
1095            ),
1096            "A bold span and a link."
1097        );
1098    }
1099
1100    // ---- section folding --------------------------------------------------
1101
1102    #[test]
1103    fn headings_nest_by_level() {
1104        let source = "# A\n\na.\n\n## B\n\nb.\n\n### C\n\nc.\n\n## D\n\nd.\n\n# E\n";
1105        assert_eq!(text(source, "h1.0.text"), "A");
1106        assert_eq!(text(source, "h1.0.paragraph.0.text"), "a.");
1107        assert_eq!(text(source, "h1.0.h2.0.text"), "B");
1108        assert_eq!(text(source, "h1.0.h2.0.h3.0.text"), "C");
1109        assert_eq!(text(source, "h1.0.h2.0.h3.0.paragraph.0.text"), "c.");
1110        // `D` closes `B` (same level) and `C` with it.
1111        assert_eq!(text(source, "h1.0.h2.1.text"), "D");
1112        assert_eq!(
1113            at(source, "h1.0.h2.1.h3.0").unwrap_err().code(),
1114            "document_path_not_found"
1115        );
1116        assert_eq!(text(source, "h1.1.text"), "E");
1117    }
1118
1119    #[test]
1120    fn a_skipped_level_keeps_its_own_name() {
1121        // `### C` under `# A` with no `## ` between: C is A's child, filed by
1122        // its own level rather than promoted to one it does not have.
1123        let source = "# A\n\n### C\n\nc.\n";
1124        assert_eq!(text(source, "h1.0.h3.0.text"), "C");
1125        assert_eq!(
1126            at(source, "h1.0.h2.0").unwrap_err().code(),
1127            "document_path_not_found"
1128        );
1129    }
1130
1131    #[test]
1132    fn a_document_opening_below_h1_has_no_h1() {
1133        // No invented level-1 wrapper: `h2` is simply where the sections are,
1134        // and a caller demanding `h1.0` fails loudly.
1135        let source = "## Only\n\ntext.\n";
1136        assert_eq!(text(source, "h2.0.text"), "Only");
1137        assert_eq!(
1138            at(source, "h1.0").unwrap_err().code(),
1139            "document_path_not_found"
1140        );
1141    }
1142
1143    #[test]
1144    fn preamble_is_always_present_and_empty_for_a_clean_file() {
1145        assert_eq!(shape("# T\n\nlead\n", "preamble.blocks"), []);
1146        assert_eq!(shape("", "preamble.blocks"), []);
1147    }
1148
1149    // ---- addressing by content --------------------------------------------
1150
1151    #[test]
1152    fn a_section_is_addressable_by_a_word_of_its_heading() {
1153        let source = "# T\n\n## A Quick Look\n\ninside look.\n\n## Supported suffixes\n\ns.\n";
1154        // Case-insensitive substring: the memorable word, not the full text.
1155        assert_eq!(text(source, "h1.0.h2.look.text"), "A Quick Look");
1156        assert_eq!(
1157            text(source, "h1.0.h2.look.paragraph.0.text"),
1158            "inside look."
1159        );
1160        assert_eq!(text(source, "h1.0.h2.SUFFIX.text"), "Supported suffixes");
1161        // Content and index address the same section.
1162        assert_eq!(
1163            at(source, "h1.0.h2.look.text").unwrap(),
1164            at(source, "h1.0.h2.0.text").unwrap()
1165        );
1166        // Matching a body paragraph does not leak in: `h2` holds only headings,
1167        // which is the whole reason the tree is not flat.
1168        assert_eq!(
1169            at(source, "h1.0.h2.inside").unwrap_err().code(),
1170            "document_slug_not_found"
1171        );
1172    }
1173
1174    #[test]
1175    fn an_empty_segment_is_not_an_address() {
1176        // `contains("")` is true for everything, so before this an empty
1177        // interpolated name resolved to whichever element happened to be
1178        // alone in the array — a confident wrong answer that only turned into
1179        // an error once a second element existed.
1180        let one = "# T\n\n## Only One\n\na\n";
1181        let two = "# T\n\n## A\n\na\n\n## B\n\nb\n";
1182        for source in [one, two] {
1183            assert_eq!(
1184                at(source, "h1.0.h2..text").unwrap_err().code(),
1185                "document_slug_not_found"
1186            );
1187        }
1188        // Named addressing still works.
1189        assert_eq!(text(two, "h1.0.h2.A.text"), "A");
1190    }
1191
1192    #[test]
1193    fn a_word_matching_several_sections_is_refused() {
1194        let source = "# T\n\n## Quick look\n\na.\n\n## Another look\n\nb.\n";
1195        let error = at(source, "h1.0.h2.look").unwrap_err();
1196        assert_eq!(error.code(), "document_ambiguous_match");
1197        // The refusal reports structural indices, never matched document text.
1198        let message = error.to_string();
1199        assert!(message.contains("indices 0, 1"), "{message}");
1200        assert!(!message.contains("Quick look"), "{message}");
1201        assert!(!message.contains("Another look"), "{message}");
1202        // A word that separates them resolves.
1203        assert_eq!(text(source, "h1.0.h2.Another.text"), "Another look");
1204    }
1205
1206    #[test]
1207    fn content_addressing_lowercases_unicode() {
1208        let source = "# T\n\n## Überblick\n\ninside.\n";
1209        assert_eq!(text(source, "h1.0.h2.ÜBER.text"), "Überblick");
1210    }
1211
1212    #[test]
1213    fn the_ask_prompt_blockquote_is_addressable_by_its_opening_words() {
1214        // The real use: this blockquote sits at no fixed index in any README,
1215        // and its position moves with every edit above it.
1216        let source = "# T\n\nThe lead.\n\n> **Ask your agent:** \"Do the thing.\"\n";
1217        assert_eq!(
1218            text(source, "h1.0.blocks.Ask your agent.text"),
1219            "Ask your agent: \"Do the thing.\""
1220        );
1221    }
1222
1223    // ---- inline flattening and block kinds --------------------------------
1224
1225    #[test]
1226    fn wrapped_paragraph_joins_onto_one_line() {
1227        assert_eq!(
1228            text("# T\n\nLead line one\nline two.\n", "h1.0.paragraph.0.text"),
1229            "Lead line one line two."
1230        );
1231    }
1232
1233    #[test]
1234    fn heading_level_is_reported_for_every_depth() {
1235        let source = "# a\n\n## b\n\n###### f\n";
1236        assert_eq!(at(source, "h1.0.level").unwrap(), Value::Integer(1));
1237        assert_eq!(at(source, "h1.0.h2.0.level").unwrap(), Value::Integer(2));
1238        assert_eq!(
1239            at(source, "h1.0.h2.0.h6.0.level").unwrap(),
1240            Value::Integer(6)
1241        );
1242    }
1243
1244    #[test]
1245    fn blockquote_flattens_its_paragraphs() {
1246        // One wrapped paragraph is one line, as the prompt convention needs.
1247        assert_eq!(
1248            shape(
1249                "> **Ask your agent:** \"Wrapped across\n> two lines.\"\n",
1250                "preamble.blocks"
1251            ),
1252            [(
1253                "blockquote".to_string(),
1254                "Ask your agent: \"Wrapped across two lines.\"".to_string()
1255            )]
1256        );
1257        // Two paragraphs are two blocks, and that boundary is structure, so it
1258        // survives as a newline rather than dissolving into a space.
1259        assert_eq!(
1260            shape("> first\n>\n> second\n", "preamble.blocks"),
1261            [("blockquote".to_string(), "first\nsecond".to_string())]
1262        );
1263    }
1264
1265    #[test]
1266    fn list_reports_its_items_and_whether_it_is_ordered() {
1267        let bullet = at("- one\n- two\n", "preamble.blocks.0").unwrap();
1268        assert_eq!(bullet.get("text").and_then(Value::as_str), Some("one\ntwo"));
1269        assert_eq!(bullet.get("ordered"), Some(&Value::Bool(false)));
1270
1271        assert_eq!(
1272            at("1. one\n2. two\n", "preamble.blocks.0")
1273                .unwrap()
1274                .get("ordered"),
1275            Some(&Value::Bool(true))
1276        );
1277
1278        // A loose list wraps each item in a paragraph and a tight one does
1279        // not. That is a rendering difference, not a content one, so the two
1280        // must read the same.
1281        assert_eq!(
1282            at("- one\n\n- two\n", "preamble.blocks.0")
1283                .unwrap()
1284                .get("text")
1285                .and_then(Value::as_str),
1286            Some("one\ntwo")
1287        );
1288
1289        // A nested list is a block inside its item, and flattens with it.
1290        assert_eq!(
1291            at("- one\n  - inner\n- two\n", "preamble.blocks.0")
1292                .unwrap()
1293                .get("text")
1294                .and_then(Value::as_str),
1295            Some("one\ninner\ntwo")
1296        );
1297    }
1298
1299    #[test]
1300    fn a_leading_metadata_block_is_its_own_kind() {
1301        // A Zola `_index.md`: the `+++` block used to flatten into two
1302        // paragraphs of the body, so `preamble` reported prose that was really
1303        // metadata and a caller reading "the first paragraph" got TOML.
1304        let toml = "+++\ntitle = \"T\"\n\n[extra]\ntagline = \"x\"\n+++\n\n# Real\n\nThe lead.\n";
1305        assert_eq!(types(toml, "preamble.blocks"), ["frontmatter".to_string()]);
1306        assert_eq!(
1307            at(toml, "preamble.blocks.0.format").unwrap(),
1308            Value::String("toml".to_string())
1309        );
1310        // Deliberately not copied into `text`: which fields it holds is TOML's
1311        // answer, and `--input-format toml-frontmatter` is how you get them.
1312        // This structural view must not bypass field-name-based redaction.
1313        assert_eq!(text(toml, "preamble.blocks.0.text"), "");
1314        // The body reads exactly as it would without the block.
1315        assert_eq!(text(toml, "h1.0.text"), "Real");
1316        assert_eq!(text(toml, "h1.0.paragraph.0.text"), "The lead.");
1317
1318        let yaml = "---\ntitle: T\n---\n\n# Real\n";
1319        assert_eq!(types(yaml, "preamble.blocks"), ["frontmatter".to_string()]);
1320        assert_eq!(
1321            at(yaml, "preamble.blocks.0.format").unwrap(),
1322            Value::String("yaml".to_string())
1323        );
1324        assert_eq!(text(yaml, "h1.0.text"), "Real");
1325    }
1326
1327    #[test]
1328    fn dashes_away_from_the_start_keep_their_commonmark_meaning() {
1329        // A setext underline and an isolated thematic break keep their
1330        // CommonMark meaning.
1331        assert_eq!(text("Setext\n---\n\nbody\n", "h2.0.text"), "Setext");
1332        assert_eq!(
1333            types("# T\n\na\n\n---\n\nb\n", "h1.0.blocks"),
1334            [
1335                "paragraph".to_string(),
1336                "rule".to_string(),
1337                "paragraph".to_string()
1338            ]
1339        );
1340    }
1341
1342    #[test]
1343    fn a_source_range_stops_at_the_block_it_names() {
1344        // pulldown-cmark runs a list's span on to where the next block starts,
1345        // so it carries the blank separator. A range is a splice instruction:
1346        // taking the separator out merges the blocks on either side. Here that
1347        // made `Lead.` and `Next Title\n====` one setext heading, swallowing
1348        // the lead paragraph into a title.
1349        let source = "- a\n  - b\n\n\nAfter.\n";
1350        assert_eq!(
1351            at(source, "preamble.blocks.0.type").unwrap(),
1352            Value::String("list".to_string())
1353        );
1354        assert_eq!(
1355            at(source, "preamble.blocks.0.source_start_line").unwrap(),
1356            Value::Integer(1)
1357        );
1358        assert_eq!(
1359            at(source, "preamble.blocks.0.source_end_line").unwrap(),
1360            Value::Integer(2)
1361        );
1362        assert_eq!(
1363            at(source, "preamble.blocks.1.source_start_line").unwrap(),
1364            Value::Integer(5)
1365        );
1366
1367        // Every other kind already ended at its own last line; assert they
1368        // still do, so the trim cannot over-correct.
1369        let mixed = "# H\n\npara\n\n```\ncode\n```\n\n> quote\n\n---\n\ntail\n";
1370        for (address, start, end) in [
1371            ("h1.0.blocks.0", 3, 3),
1372            ("h1.0.blocks.1", 5, 7),
1373            ("h1.0.blocks.2", 9, 9),
1374            ("h1.0.blocks.3", 11, 11),
1375            ("h1.0.blocks.4", 13, 13),
1376        ] {
1377            assert_eq!(
1378                at(mixed, &format!("{address}.source_start_line")).unwrap(),
1379                Value::Integer(start),
1380                "{address} start"
1381            );
1382            assert_eq!(
1383                at(mixed, &format!("{address}.source_end_line")).unwrap(),
1384                Value::Integer(end),
1385                "{address} end"
1386            );
1387        }
1388    }
1389
1390    #[test]
1391    fn gfm_table_rows_are_a_paragraph() {
1392        // No extensions: a table is not a block kind here, and the pipe rows
1393        // are a paragraph. That is the specification's reading, not a gap.
1394        assert_eq!(
1395            shape("| a | b |\n|---|---|\n| 1 | 2 |\n", "preamble.blocks"),
1396            [(
1397                "paragraph".to_string(),
1398                "| a | b | |---|---| | 1 | 2 |".to_string()
1399            )]
1400        );
1401        assert_eq!(
1402            shape("| a | b |\n|---|---|\n| 1 | 2 |\n", "preamble.paragraph"),
1403            [(
1404                "paragraph".to_string(),
1405                "| a | b | |---|---| | 1 | 2 |".to_string()
1406            )]
1407        );
1408    }
1409
1410    #[test]
1411    fn badge_syntax_remains_in_the_paragraph_view() {
1412        let source = "# T\n\n[![CI](a.svg)](b)\n\nThe lead.\n";
1413        assert_eq!(
1414            shape(source, "h1.0.paragraph"),
1415            [
1416                ("paragraph".to_string(), "CI".to_string()),
1417                ("paragraph".to_string(), "The lead.".to_string()),
1418            ]
1419        );
1420    }
1421
1422    // ---- source line ranges ----------------------------------------------
1423
1424    #[test]
1425    fn atx_heading_and_blocks_report_inclusive_source_lines() {
1426        let source = "# Title\n\nLead line one\nline two.\n\n```rs\nfn main() {}\n```\n";
1427        assert_eq!(integer(source, "h1.0.source_start_line"), 1);
1428        assert_eq!(integer(source, "h1.0.source_end_line"), 8);
1429        assert_eq!(integer(source, "h1.0.source_start_line"), 1);
1430        assert_eq!(integer(source, "h1.0.heading_end_line"), 1);
1431        assert_eq!(integer(source, "h1.0.paragraph.0.source_start_line"), 3);
1432        assert_eq!(integer(source, "h1.0.paragraph.0.source_end_line"), 4);
1433        assert_eq!(integer(source, "h1.0.blocks.1.source_start_line"), 6);
1434        assert_eq!(integer(source, "h1.0.blocks.1.source_end_line"), 8);
1435    }
1436
1437    #[test]
1438    fn setext_heading_range_includes_its_underline() {
1439        let source = "My Project\n==========\n\nThe synopsis.\n\n## Install\n";
1440        assert_eq!(integer(source, "h1.0.source_start_line"), 1);
1441        assert_eq!(integer(source, "h1.0.heading_end_line"), 2);
1442        assert_eq!(integer(source, "h1.0.source_end_line"), 6);
1443        assert_eq!(integer(source, "h1.0.h2.0.source_start_line"), 6);
1444        assert_eq!(integer(source, "h1.0.h2.0.source_end_line"), 6);
1445        assert_eq!(integer(source, "h1.0.paragraph.0.source_start_line"), 4);
1446        assert_eq!(integer(source, "h1.0.paragraph.0.source_end_line"), 4);
1447    }
1448
1449    #[test]
1450    fn line_ranges_are_utf8_safe_and_newline_style_independent() {
1451        let source = "# 中文标题\r\n\r\n这是首段,\r\n也是首段。\r\n\r\n## 安装";
1452        assert_eq!(integer(source, "h1.0.source_start_line"), 1);
1453        assert_eq!(integer(source, "h1.0.heading_end_line"), 1);
1454        assert_eq!(integer(source, "h1.0.paragraph.0.source_start_line"), 3);
1455        assert_eq!(integer(source, "h1.0.paragraph.0.source_end_line"), 4);
1456        assert_eq!(integer(source, "h1.0.h2.0.source_start_line"), 6);
1457        assert_eq!(integer(source, "h1.0.h2.0.heading_end_line"), 6);
1458    }
1459
1460    #[test]
1461    fn nesting_beyond_the_block_depth_is_refused_not_a_stack_overflow() {
1462        let nested = |depth: usize| format!("# T\n{}x\n", "> ".repeat(depth));
1463        // The heading closes first, so the innermost paragraph adds one level.
1464        assert_eq!(text(&nested(47), "h1.0.blockquote.0.text"), "x");
1465        for depth in [48, 100_000] {
1466            let error = load(&nested(depth)).unwrap_err();
1467            assert_eq!(error.code(), "document_source_refused");
1468            assert!(error.to_string().contains("48 levels"), "{error}");
1469        }
1470        let error = load(&format!("{}x\n", "- ".repeat(100_000))).unwrap_err();
1471        assert_eq!(error.code(), "document_source_refused");
1472    }
1473
1474    #[test]
1475    fn a_bare_carriage_return_is_refused_rather_than_numbered() {
1476        // CommonMark ends a line at a bare `\r`; sed, awk, wc, head, and git
1477        // do not. These numbers exist to be handed to those, so for such a
1478        // file no single number is right for both readers — here `Lead` and
1479        // `## End` would share a line, and a splice by that number would cut
1480        // the wrong text silently.
1481        let error = load("# T\r\rLead\rcontinued\r\r## End").unwrap_err();
1482        // Its own code, not `document_parse_failed`: the file is valid
1483        // CommonMark and afdata is declining to number it, so a reader told
1484        // "parse failed" would go hunting for a syntax error that is not there.
1485        assert_eq!(error.code(), "document_source_refused");
1486        assert!(error.to_string().contains("carriage return"), "{error}");
1487        // The way out survives redaction. This detail is written here, about
1488        // the file's line endings, and holds no document text — dropping it
1489        // left `failed to parse Markdown` and nothing to act on.
1490        assert!(
1491            error.redacted_message().contains("CRLF line endings"),
1492            "{}",
1493            error.redacted_message()
1494        );
1495
1496        // The endings every current tool writes are unaffected, and both
1497        // rules agree on them.
1498        let crlf = "# T\r\n\r\nLead\r\ncontinued\r\n\r\n## End\r\n";
1499        assert_eq!(integer(crlf, "h1.0.paragraph.0.source_start_line"), 3);
1500        assert_eq!(integer(crlf, "h1.0.paragraph.0.source_end_line"), 4);
1501        assert_eq!(integer(crlf, "h1.0.h2.0.source_start_line"), 6);
1502
1503        // No final newline still numbers its last line.
1504        let bare = "# T\n\nLead";
1505        assert_eq!(integer(bare, "h1.0.paragraph.0.source_end_line"), 3);
1506    }
1507
1508    #[test]
1509    fn frontmatter_range_includes_both_delimiters() {
1510        let source = "---\ntitle: T\nnested:\n  token_secret: hidden\n---\n\n# T\n";
1511        assert_eq!(integer(source, "preamble.blocks.0.source_start_line"), 1);
1512        assert_eq!(integer(source, "preamble.blocks.0.source_end_line"), 5);
1513        assert_eq!(text(source, "preamble.blocks.0.text"), "");
1514
1515        let source = "+++\r\n\r\ntoken_secret = \"canary\"\r\n+++\t\r\nTitle\r\n=====\r\n";
1516        assert_eq!(integer(source, "preamble.blocks.0.source_start_line"), 1);
1517        assert_eq!(integer(source, "preamble.blocks.0.source_end_line"), 4);
1518        assert_eq!(text(source, "preamble.blocks.0.text"), "");
1519        assert_eq!(integer(source, "h1.0.source_start_line"), 5);
1520        assert_eq!(integer(source, "h1.0.heading_end_line"), 6);
1521        assert_eq!(text(source, "h1.0.text"), "Title");
1522
1523        let source = "---\n---\n---\n\n# T";
1524        assert_eq!(types(source, "preamble.blocks"), ["frontmatter", "rule"]);
1525        assert_eq!(integer(source, "h1.0.source_start_line"), 5);
1526
1527        let source = "---\ntitle: T\n...\n\n# T\n\n---\n";
1528        assert_eq!(integer(source, "preamble.blocks.0.source_end_line"), 3);
1529        assert_eq!(integer(source, "h1.0.source_start_line"), 5);
1530        assert_eq!(types(source, "h1.0.blocks"), ["rule"]);
1531
1532        let source = "---\n\n# Body\n";
1533        assert_eq!(types(source, "preamble.blocks"), ["rule"]);
1534        assert_eq!(text(source, "h1.0.text"), "Body");
1535
1536        let source = "---\n\n# Inside the fences\n\n---\n\n# Body\n";
1537        assert_eq!(types(source, "preamble.blocks"), ["frontmatter"]);
1538        assert_eq!(text(source, "h1.0.text"), "Body");
1539    }
1540
1541    #[test]
1542    fn thematic_break_is_a_block_with_no_text() {
1543        assert_eq!(
1544            shape("# T\n\na\n\n---\n\nb\n", "h1.0.blocks"),
1545            [
1546                ("paragraph".to_string(), "a".to_string()),
1547                ("rule".to_string(), String::new()),
1548                ("paragraph".to_string(), "b".to_string()),
1549            ]
1550        );
1551        // The paragraph view skips it, so "the second paragraph" stays the
1552        // second paragraph.
1553        assert_eq!(
1554            shape("# T\n\na\n\n---\n\nb\n", "h1.0.paragraph"),
1555            [
1556                ("paragraph".to_string(), "a".to_string()),
1557                ("paragraph".to_string(), "b".to_string()),
1558            ]
1559        );
1560    }
1561
1562    #[test]
1563    fn a_byte_order_mark_makes_the_first_block_a_paragraph() {
1564        // CommonMark does not strip a BOM, so `\u{feff}# Title` is not a
1565        // heading. Pinned because a Windows editor writes one silently: the
1566        // file then has no section at all, which fails loudly — the outcome to
1567        // keep, against publishing "\u{feff}Title" as a name.
1568        assert_eq!(
1569            types("\u{feff}# Title\n\nlead\n", "preamble.blocks"),
1570            ["paragraph".to_string(), "paragraph".to_string()]
1571        );
1572    }
1573
1574    #[test]
1575    fn empty_document_has_no_blocks() {
1576        assert_eq!(shape("", "preamble.blocks"), []);
1577        assert_eq!(shape("\n\n   \n", "preamble.blocks"), []);
1578    }
1579
1580    #[test]
1581    fn code_block_keeps_its_lines_and_drops_one_trailing_newline() {
1582        assert_eq!(
1583            shape("```\nline one\nline two\n```\n", "preamble.blocks"),
1584            [("code".to_string(), "line one\nline two".to_string())]
1585        );
1586    }
1587
1588    /// `text` flattens inline markup; `inlines` keeps exactly what that drops:
1589    /// which words are code, where a link points, what is an image.
1590    #[test]
1591    fn inlines_keep_what_text_flattens() {
1592        let source =
1593            "See [the **docs**](docs.md), ![alt *x*](img.png) and `code` <b>b</b>\\\nend\n";
1594        assert_eq!(
1595            text(source, "preamble.paragraph.0.text"),
1596            "See the docs, alt x and code b end"
1597        );
1598        let kinds = |path: &str| -> Vec<(String, String)> {
1599            at(source, path)
1600                .unwrap()
1601                .as_array()
1602                .unwrap()
1603                .iter()
1604                .map(|node| {
1605                    (
1606                        node.get("type")
1607                            .and_then(Value::as_str)
1608                            .unwrap()
1609                            .to_string(),
1610                        node.get("text")
1611                            .and_then(Value::as_str)
1612                            .unwrap()
1613                            .to_string(),
1614                    )
1615                })
1616                .collect()
1617        };
1618        let pairs = |items: &[(&str, &str)]| -> Vec<(String, String)> {
1619            items
1620                .iter()
1621                .map(|(kind, text)| (kind.to_string(), text.to_string()))
1622                .collect()
1623        };
1624        assert_eq!(
1625            kinds("preamble.paragraph.0.inlines"),
1626            pairs(&[
1627                ("text", "See "),
1628                ("link", "the docs"),
1629                ("text", ", "),
1630                ("image", "alt x"),
1631                ("text", " and "),
1632                ("code", "code"),
1633                ("text", " "),
1634                ("html", "<b>"),
1635                ("text", "b"),
1636                ("html", "</b>"),
1637                ("line_break", ""),
1638                ("text", "end"),
1639            ])
1640        );
1641        assert_eq!(
1642            kinds("preamble.paragraph.0.inlines.docs.inlines"),
1643            pairs(&[("text", "the "), ("strong", "docs")])
1644        );
1645        assert_eq!(
1646            text(source, "preamble.paragraph.0.inlines.docs.destination_url"),
1647            "docs.md"
1648        );
1649        assert_eq!(
1650            text(source, "preamble.paragraph.0.inlines.3.destination_url"),
1651            "img.png"
1652        );
1653        // Alt text is plain text when rendered, so an image has no children.
1654        assert!(
1655            at(source, "preamble.paragraph.0.inlines.3.inlines").is_err(),
1656            "an image reports flattened alt text only"
1657        );
1658    }
1659
1660    #[test]
1661    fn a_heading_and_its_section_report_inlines() {
1662        let source = "# Run `serve` now\n";
1663        assert_eq!(text(source, "h1.0.text"), "Run serve now");
1664        assert_eq!(text(source, "h1.0.inlines.1.type"), "code");
1665        assert_eq!(text(source, "h1.0.inlines.1.text"), "serve");
1666    }
1667
1668    /// A soft break is a wrapped line, which is presentation: it joins the
1669    /// surrounding text node rather than becoming a node of its own.
1670    #[test]
1671    fn a_soft_break_joins_adjacent_text() {
1672        assert_eq!(
1673            text("one\ntwo\n", "preamble.paragraph.0.inlines.0.text"),
1674            "one two"
1675        );
1676        assert!(at("one\ntwo\n", "preamble.paragraph.0.inlines.1").is_err());
1677    }
1678
1679    /// A code fence inside a list item or a blockquote is still a `code`
1680    /// block: containers report their children, not only flattened text.
1681    #[test]
1682    fn containers_report_their_child_blocks() {
1683        let source = "- item\n\n  ```bash\n  nested\n  ```\n\n> ```json\n> {}\n> ```\n";
1684        assert_eq!(text(source, "preamble.blocks.0.blocks.0.type"), "item");
1685        assert_eq!(
1686            text(source, "preamble.blocks.0.blocks.0.blocks.1.type"),
1687            "code"
1688        );
1689        assert_eq!(
1690            text(source, "preamble.blocks.0.blocks.0.blocks.1.language"),
1691            "bash"
1692        );
1693        assert_eq!(
1694            text(source, "preamble.blocks.0.blocks.0.blocks.1.text"),
1695            "nested"
1696        );
1697        assert_eq!(
1698            integer(
1699                source,
1700                "preamble.blocks.0.blocks.0.blocks.1.source_start_line"
1701            ),
1702            3
1703        );
1704        assert_eq!(text(source, "preamble.blocks.1.blocks.0.type"), "code");
1705        assert_eq!(text(source, "preamble.blocks.1.blocks.0.language"), "json");
1706        assert_eq!(text(source, "preamble.blocks.1.blocks.0.text"), "{}");
1707        // The flattened view is unchanged.
1708        assert_eq!(text(source, "preamble.blocks.0.text"), "item\nnested");
1709    }
1710
1711    /// The reported tree of the deepest file the reader accepts must still be
1712    /// readable as JSON, inside a protocol envelope, by a reader that stops at
1713    /// 128 levels — or `afdata get` emits documents it cannot read back.
1714    #[test]
1715    fn the_deepest_accepted_file_reports_a_tree_json_can_read_back() {
1716        fn depth(value: &Value) -> usize {
1717            match value {
1718                Value::Array(items) => 1 + items.iter().map(depth).max().unwrap_or(0),
1719                Value::Object(fields) => 1 + fields.values().map(depth).max().unwrap_or(0),
1720                _ => 0,
1721            }
1722        }
1723        let headings = "# a\n## b\n### c\n#### d\n##### e\n###### f\n";
1724        // A list item is two levels (list, item), the paragraph inside one more.
1725        let deepest = [
1726            format!("{headings}{}x\n", "> ".repeat(MAX_BLOCK_DEPTH - 1)),
1727            format!("{headings}{}x\n", "- ".repeat((MAX_BLOCK_DEPTH - 1) / 2)),
1728            format!("{headings}{}*x*\n", "> ".repeat(MAX_BLOCK_DEPTH - 3)),
1729        ];
1730        for source in deepest {
1731            let tree = load(&source).unwrap();
1732            assert!(depth(&tree) <= 112, "{} levels", depth(&tree));
1733            let json = serde_json::to_string(&tree).unwrap();
1734            let enveloped = format!("{{\"kind\":\"result\",\"result\":{{\"value\":{json}}}}}");
1735            serde_json::from_str::<serde_json::Value>(&enveloped).unwrap();
1736        }
1737    }
1738
1739    #[test]
1740    fn inline_nesting_counts_toward_the_depth_limit() {
1741        let nested = |depth: usize| format!("{}x{}\n", "*".repeat(depth), "*".repeat(depth));
1742        assert!(load(&nested(8)).is_ok());
1743        let error = load(&nested(400)).unwrap_err();
1744        assert_eq!(error.code(), "document_source_refused");
1745    }
1746}