Skip to main content

memstead_base/entity/
parser.rs

1//! Markdown → Entity parser. Handles YAML frontmatter, sections, wiki-links.
2//!
3//! Key design decisions:
4//! - Hand-rolled YAML frontmatter parser (NOT serde_yaml) to match JS type coercion
5//! - Code blocks are masked before section/link detection to prevent false matches
6//! - The parser is schema-aware: it uses the schema to determine catch-all sections
7
8use std::collections::{BTreeMap, HashMap, HashSet};
9use std::ops::Range;
10use std::path::Path;
11use std::sync::OnceLock;
12
13use indexmap::IndexMap;
14use regex::Regex;
15use sha2::{Digest, Sha256};
16
17use memstead_schema::TypeDefinition;
18
19use super::id::{WikiLinkError, file_path_to_id, wiki_link_to_id, wiki_link_to_id_lenient};
20use super::{Entity, EntityId, HeadingSpan, MetadataValue, ParseResult, Relationship};
21
22/// Parse a markdown string into an Entity.
23pub fn parse_markdown(
24    content: &str,
25    relative_path: &str,
26    schema: &TypeDefinition,
27    mem: &str,
28) -> Result<ParseResult, ParseError> {
29    let id = file_path_to_id(relative_path, mem);
30
31    // Compute content hash from raw markdown
32    let content_hash = compute_hash(content);
33
34    // Extract YAML frontmatter FIRST — frontmatter is not markdown, and
35    // handing it to a CommonMark parser invents block structure that is
36    // not there (a value line that reads as a fence opener would open a
37    // code block running past the closing `---` and mask the whole
38    // body). Only the body is markdown, so only the body is masked.
39    let (metadata, body) = split_frontmatter(content)?;
40    let masked_body = mask_code_blocks(&body);
41
42    // Extract title (first # heading)
43    let title = extract_title(&body, &masked_body).unwrap_or_else(|| id.name().to_string());
44
45    // Split body into ## sections (match against masked, slice from original).
46    // Duplicate `## Heading` lines whose slug matches a schema-declared key
47    // become `DuplicateSectionHeading` warnings below; first-wins is the
48    // resolution policy.
49    let (sections_map, duplicate_headings, raw_section_headings) =
50        split_sections(&body, &masked_body);
51
52    // Parse typed relationships from the Relationships section.
53    // The entity-id collector lets the parser surface
54    // `AMBIGUOUS_DESCRIPTION_DELIMITER` warnings against a concrete
55    // source so boot / reload / attach sites can report them in
56    // `LoadCollector::warnings`.
57    let rel_heading_key = "relationships";
58    let entity_id_for_rel_warnings = file_path_to_id(relative_path, mem);
59    let (relationships, rel_parse_warnings) = parse_relationships_with_warnings(
60        sections_map
61            .get(rel_heading_key)
62            .map(|(_, content)| content.as_str())
63            .unwrap_or(""),
64        mem,
65        Some(&entity_id_for_rel_warnings),
66    );
67
68    // Build catch-all section content
69    let catch_all_content = build_catch_all(&sections_map, schema);
70
71    // Extract schema-defined section values.
72    // IndexMap + this loop order is what guarantees sections iterate in the
73    // schema's declared order downstream. Do not change to a HashMap.
74    // No re-trim here: `split_sections` already normalised each value
75    // (leading blank lines dropped, first visible line's bytes kept,
76    // trailing trimmed), and `build_catch_all` joins such values. A
77    // second full trim silently promoted a whitespace-prefixed first
78    // line (`\u{b}` + backticks) to column 0, where the CommonMark
79    // referee suddenly saw a fence opener that the stored form did not
80    // have — the section structure then shifted between rounds (fuzz
81    // finding, long tier, corpus member `crash-fd71330e…`).
82    let mut result_sections = IndexMap::new();
83    for s in &schema.sections {
84        if s.catch_all {
85            // The catch-all key stays present when its own heading was in
86            // the document or any non-schema section fed it — an absent
87            // catch-all with no absorbed content stays absent, like every
88            // other section below.
89            if sections_map.contains_key(s.key.as_str()) || !catch_all_content.trim().is_empty() {
90                result_sections.insert(s.key.clone(), catch_all_content.clone());
91            }
92        } else if let Some((_, content)) = sections_map.get(s.key.as_str()) {
93            result_sections.insert(s.key.clone(), content.clone());
94        }
95        // A declared section whose heading the document does not carry is
96        // ABSENT, not present-with-empty. Materialising every declared key
97        // here (the pre-fix `unwrap_or_default`) made "no heading" and
98        // "empty heading" the same entity, so the generator re-emitted a
99        // scaffold heading for every declared-but-unwritten section and
100        // `sections_unset` could not close one — the removed key came back
101        // on the next round-trip.
102    }
103
104    // Parse metadata values with type coercion
105    let mut parsed_metadata = parse_metadata(&metadata);
106
107    // Determine type from metadata or default, and ensure it's in metadata.
108    // The entity's `type:` frontmatter key takes precedence over the mem's
109    // default type — parse-time resolution means each file is authoritative
110    // about its own type.
111    let type_name = parsed_metadata
112        .get("type")
113        .and_then(|v| v.as_str())
114        .unwrap_or(schema.name.as_str())
115        .to_string();
116    parsed_metadata.insert("type".to_string(), MetadataValue::String(type_name.clone()));
117
118    // Extract inline wiki-links from text fields (excluding relationships section)
119    let inline_link_text: String = schema
120        .text_fields
121        .iter()
122        .filter_map(|f| result_sections.get(f.as_str()))
123        .cloned()
124        .collect::<Vec<_>>()
125        .join("\n");
126    // Read-time scan: tolerate pre-strict on-disk drift so loaders
127    // and dangling-link reporters keep working against legacy
128    // entities. The mutation pipeline re-extracts strictly via
129    // `extract_inline_links` and refuses on grammar violations.
130    let inline_links = extract_inline_links_lenient(&inline_link_text, mem);
131
132    // Filter out targets already covered by explicit relationships
133    let explicit_targets: HashSet<_> = relationships.iter().map(|r| &r.target).collect();
134    let inline_links: Vec<EntityId> = inline_links
135        .into_iter()
136        .filter(|link| !explicit_targets.contains(link))
137        .collect();
138
139    // Extract H3–H6 spans per section for search-time heading-path attribution.
140    // Side-struct only: regenerated every parse, never persisted.
141    let heading_spans = extract_heading_spans(&result_sections);
142
143    // Build warnings for duplicate-heading occurrences whose slug matches a
144    // schema-declared key. Catch-all keys (`s.catch_all`) absorb arbitrary
145    // headings by design, so duplicates there are not surfaced.
146    let declared_keys: HashSet<&str> = schema
147        .sections
148        .iter()
149        .filter(|s| !s.catch_all)
150        .map(|s| s.key.as_str())
151        .collect();
152    let entity_id_for_warnings = file_path_to_id(relative_path, mem);
153    let mut parse_warnings: Vec<crate::ops::WarningHint> = duplicate_headings
154        .into_iter()
155        .filter(|d| declared_keys.contains(d.key.as_str()))
156        .map(|d| crate::ops::WarningHint::DuplicateSectionHeading {
157            entity_id: entity_id_for_warnings.clone(),
158            section_key: d.key,
159            heading: d.heading,
160            occurrences: d.occurrences,
161        })
162        .collect();
163    parse_warnings.extend(rel_parse_warnings);
164
165    let entity = Entity {
166        id,
167        title,
168        entity_type: type_name,
169        mem: mem.to_string(),
170        file_path: relative_path.to_string(),
171        metadata: parsed_metadata,
172        sections: result_sections,
173        relationships,
174        content_hash,
175        stub: false,
176        stub_kind: None,
177        heading_spans,
178        raw_section_headings,
179    };
180
181    Ok(ParseResult {
182        entity,
183        inline_links,
184        parse_warnings,
185    })
186}
187
188/// Parse an entity from a file on disk.
189pub fn parse_file(
190    path: &Path,
191    mem_dir: &Path,
192    schema: &TypeDefinition,
193    mem: &str,
194) -> Result<ParseResult, ParseError> {
195    let content = std::fs::read_to_string(path)?;
196    let relative_path = path.strip_prefix(mem_dir).unwrap_or(path).to_string_lossy();
197    parse_markdown(&content, &relative_path, schema, mem)
198}
199
200// ---------------------------------------------------------------------------
201// Frontmatter
202// ---------------------------------------------------------------------------
203
204// ---------------------------------------------------------------------------
205// The frontmatter delimiter contract — one implementation
206// ---------------------------------------------------------------------------
207
208/// What a document's leading `---` block turned out to be.
209///
210/// The three historical readers differed only in what they did with these
211/// three cases, never in how they found them: the tolerant path degraded on
212/// both failures, the peek borrowed and degraded, the strict path refused with
213/// a different typed error for each. That difference belongs to the wrappers;
214/// the arithmetic below belongs here, once.
215#[derive(Debug, PartialEq, Eq)]
216pub enum Frontmatter<'a> {
217    /// A closed block. Both slices borrow the input.
218    Present { meta: &'a str, body: &'a str },
219    /// The document does not open with `---` on its first line.
220    NoOpeningDelimiter,
221    /// It opens but never closes with `\n---`.
222    Unclosed,
223}
224
225/// Split a document at its frontmatter delimiters.
226///
227/// Returns the byte-order-mark-stripped input alongside the verdict, because
228/// every caller that degrades to "the whole document is body" must degrade to
229/// the *stripped* document: a marked local file once parsed as all body and
230/// lost its entire frontmatter precisely because two paths disagreed about
231/// where the document began. **The mark is stripped here and nowhere else.**
232///
233/// Both returned slices are suffixes of the returned `stripped` slice, which
234/// is itself a suffix of `content`. Two callers recover the frontmatter prefix
235/// by subtracting the body's length, so a core that copied or normalised
236/// anything would break them silently.
237pub fn split_frontmatter_core(content: &str) -> (&str, Frontmatter<'_>) {
238    let content = content.strip_prefix('\u{feff}').unwrap_or(content);
239
240    let after_open = if content.starts_with("---\r\n") {
241        5
242    } else if content.starts_with("---\n") {
243        4
244    } else {
245        return (content, Frontmatter::NoOpeningDelimiter);
246    };
247
248    let rest = &content[after_open..];
249    let Some(close_pos) = rest.find("\n---") else {
250        return (content, Frontmatter::Unclosed);
251    };
252    let meta = &rest[..close_pos];
253
254    let body_rest = &rest[close_pos + "\n---".len()..];
255    let body = body_rest
256        .strip_prefix("\r\n")
257        .or_else(|| body_rest.strip_prefix('\n'))
258        .unwrap_or(body_rest);
259
260    (content, Frontmatter::Present { meta, body })
261}
262
263/// The frontmatter block and the body of a document, both borrowed, or
264/// `None` when the document carries no closed frontmatter (no opening
265/// fence on its first line, or an opening fence never closed). The one
266/// entry point every reader outside this module uses; the contract is
267/// [`split_frontmatter_core`]'s: a byte-order mark is skipped, CRLF and LF
268/// documents both split, the fence counts only at the start of the
269/// document, and the body starts after the closing fence's line break.
270pub fn frontmatter_parts(content: &str) -> Option<(&str, &str)> {
271    match split_frontmatter_core(content) {
272        (_, Frontmatter::Present { meta, body }) => Some((meta, body)),
273        _ => None,
274    }
275}
276
277/// Extract the `type:` value from frontmatter without running the full parser.
278///
279/// Used by the loader to resolve each file's type independently — the mem
280/// config's default type is only a fallback for files that don't declare one.
281/// Returns None if there's no frontmatter, no `type:` line, or it's empty.
282pub fn peek_type_from_frontmatter(content: &str) -> Option<String> {
283    let (_, split) = split_frontmatter_core(content);
284    let Frontmatter::Present {
285        meta: frontmatter, ..
286    } = split
287    else {
288        return None;
289    };
290
291    for line in frontmatter.lines() {
292        let trimmed = line.trim();
293        if trimmed.is_empty() || trimmed.starts_with('#') {
294            continue;
295        }
296        let Some(colon_idx) = trimmed.find(':') else {
297            continue;
298        };
299        let key = trimmed[..colon_idx].trim();
300        if key != "type" {
301            continue;
302        }
303        let mut value = trimmed[colon_idx + 1..].trim();
304        if let Some(hash_idx) = value.find('#') {
305            value = value[..hash_idx].trim();
306        }
307        let value = value.trim_matches(|c| c == '"' || c == '\'');
308        if value.is_empty() {
309            return None;
310        }
311        return Some(value.to_string());
312    }
313    None
314}
315
316/// Peek the entity title (first `# ` heading in the body) and type
317/// (`type:` frontmatter field) from raw markdown without running the
318/// full schema-aware parser. Used by surfaces that read a markdown blob
319/// outside the in-memory store — e.g. `memstead_diff` walking git trees
320/// between two arbitrary refs, where the store snapshot (current HEAD)
321/// is not a valid source for a non-HEAD ref. Returns `None` for `title`
322/// when the body carries no `# ` heading and `None` for `entity_type`
323/// when the frontmatter lacks a non-empty `type:`.
324pub fn peek_title_and_type(content: &str) -> (Option<String>, Option<String>) {
325    let entity_type = peek_type_from_frontmatter(content);
326    let body = body_after_frontmatter(content);
327    let title = extract_title(body, &mask_code_blocks(body));
328    (title, entity_type)
329}
330
331/// Return the body slice after a leading `---` frontmatter block, or
332/// the whole input when no frontmatter is present. Mirrors the offset
333/// arithmetic in [`split_frontmatter`] but borrows rather than
334/// allocating — a scan needs to read, not own.
335///
336/// **Call this before handing a whole entity file to any markdown
337/// reader in this module.** Frontmatter is not markdown: a CommonMark
338/// parser reads block structure into it that is not there, and a YAML
339/// value that looks like a fence opener (legal at 1–3 spaces) opens a
340/// code block that runs past the `---` terminator to end of file,
341/// masking the entire body. Every reader here — [`mask_code_blocks`],
342/// [`extract_inline_links`], [`extract_inline_links_lenient`],
343/// [`split_sections`] — expects a body, and the callers inside the
344/// engine that hold one already pass section bodies. A caller holding
345/// a raw file or git blob does not, and must trim it here first.
346pub fn body_after_frontmatter(content: &str) -> &str {
347    match split_frontmatter_core(content) {
348        (_, Frontmatter::Present { body, .. }) => body,
349        (stripped, _) => stripped,
350    }
351}
352
353/// Split content into frontmatter metadata string and body.
354/// Returns (metadata_string, body). Both boundaries are found in the
355/// raw content — the caller masks the body afterwards.
356pub(crate) fn split_frontmatter(content: &str) -> Result<(String, String), ParseError> {
357    // The every-local-read path: it never refuses. A document with no opening
358    // delimiter, or an unclosed block, is entirely body — a hand-edited file
359    // without frontmatter must still load.
360    match split_frontmatter_core(content) {
361        (_, Frontmatter::Present { meta, body }) => Ok((meta.to_string(), body.to_string())),
362        (stripped, _) => Ok((String::new(), stripped.to_string())),
363    }
364}
365
366/// Parse metadata key-value pairs with JS-compatible type coercion.
367///
368/// Handles: strings, integers, floats, booleans.
369/// Strips inline comments (`value # comment`) and quotes (`"value"`).
370fn parse_metadata(text: &str) -> IndexMap<String, MetadataValue> {
371    let mut meta = IndexMap::new();
372    if text.is_empty() {
373        return meta;
374    }
375
376    for line in text.lines() {
377        let trimmed = line.trim();
378        // Skip empty lines, comments, heading markers, delimiters
379        if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("---") {
380            continue;
381        }
382
383        let Some(colon_idx) = trimmed.find(':') else {
384            continue;
385        };
386
387        let key = trimmed[..colon_idx].trim().to_string();
388        let raw_value = trimmed[colon_idx + 1..].trim();
389
390        // Strip inline comments (# not inside the value)
391        let value = strip_inline_comment(raw_value).trim().to_string();
392
393        if value.is_empty() {
394            meta.insert(key, MetadataValue::String(String::new()));
395            continue;
396        }
397
398        // Type coercion (matching JS parser behavior exactly)
399        if value == "true" {
400            meta.insert(key, MetadataValue::Bool(true));
401        } else if value == "false" {
402            meta.insert(key, MetadataValue::Bool(false));
403        } else if is_float_literal(&value) {
404            if let Ok(f) = value.parse::<f64>() {
405                meta.insert(key, MetadataValue::Float(f));
406            } else {
407                meta.insert(key, MetadataValue::String(strip_quotes(&value)));
408            }
409        } else if is_integer_literal(&value) {
410            if let Ok(n) = value.parse::<i64>() {
411                meta.insert(key, MetadataValue::Integer(n));
412            } else {
413                meta.insert(key, MetadataValue::String(strip_quotes(&value)));
414            }
415        } else {
416            meta.insert(key, MetadataValue::String(strip_quotes(&value)));
417        }
418    }
419
420    meta
421}
422
423/// Check if a string matches the JS float regex: /^-?\d+\.\d+$/
424fn is_float_literal(s: &str) -> bool {
425    let s = s.strip_prefix('-').unwrap_or(s);
426    if let Some((before, after)) = s.split_once('.') {
427        !before.is_empty()
428            && before.chars().all(|c| c.is_ascii_digit())
429            && !after.is_empty()
430            && after.chars().all(|c| c.is_ascii_digit())
431    } else {
432        false
433    }
434}
435
436/// Check if a string matches the JS integer regex: /^-?\d+$/
437fn is_integer_literal(s: &str) -> bool {
438    let s = s.strip_prefix('-').unwrap_or(s);
439    !s.is_empty() && s.chars().all(|c| c.is_ascii_digit())
440}
441
442/// Would `parse_metadata` coerce this raw value away from
443/// `MetadataValue::String`? Exposed so the generator can decide whether
444/// to YAML-quote a string value that would otherwise round-trip as
445/// Integer / Float / Bool. Kept co-located with the coercion rules so
446/// the two cannot drift.
447pub(crate) fn would_coerce_from_string(s: &str) -> bool {
448    s == "true" || s == "false" || is_integer_literal(s) || is_float_literal(s)
449}
450
451/// Strip inline comments: `value # comment` → `value`.
452fn strip_inline_comment(s: &str) -> &str {
453    // Find ` #` pattern (space followed by #)
454    // But be careful not to strip inside quoted strings
455    if let Some(idx) = s.find(" #") {
456        s[..idx].trim_end()
457    } else {
458        s
459    }
460}
461
462/// Strip surrounding quotes: `"value"` or `'value'` → `value`.
463/// A lone quote character is not a quoted value — `len >= 2` keeps the
464/// slice in bounds (a 1-char `"` satisfies both starts_with and ends_with).
465fn strip_quotes(s: &str) -> String {
466    if s.len() >= 2
467        && ((s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')))
468    {
469        s[1..s.len() - 1].to_string()
470    } else {
471        s.to_string()
472    }
473}
474
475// ---------------------------------------------------------------------------
476// Code block masking
477// ---------------------------------------------------------------------------
478
479/// Mask every CommonMark code block by replacing its bytes with spaces
480/// (preserves line count and byte offsets). Handles unclosed blocks
481/// safely — they mask to end of text.
482///
483/// The definition lives in [`crate::markdown`] — one referee for every
484/// content reader in the engine. Re-exported here because this module's
485/// callers are the historical ones.
486pub use crate::markdown::{mask_code_blocks, mask_code_blocks_and_spans};
487
488// ---------------------------------------------------------------------------
489// Merge-conflict detection
490// ---------------------------------------------------------------------------
491
492/// True when `text` — a whole entity file — carries a complete git
493/// merge-conflict block: an ordered `<<<<<<< …` / `=======` /
494/// `>>>>>>> …` triple at line starts.
495///
496/// The frontmatter is scanned **raw** and the body over
497/// [`mask_code_blocks`] output. Both halves of that split are
498/// load-bearing:
499///
500/// - Masking the body is why a code example documenting conflict
501///   markers never trips the check. It is a legibility trade-off, not
502///   a soundness one: a real conflict whose markers all fall inside
503///   one code block goes undetected (the file then loads/degrades
504///   exactly as it did before this check existed) — git writes markers
505///   without regard for fences, so that shape is rare, while marker
506///   examples in documentation entities are not.
507/// - Frontmatter is **not** masked, because frontmatter is not
508///   markdown. Handing it to a CommonMark parser invents block
509///   structure that is not there: a YAML value that reads as a fence
510///   opener (legal at 1–3 spaces) opens a code block that runs past
511///   the `---` terminator to end of file and blanks the entire body,
512///   markers and all — a conflicted file would then load with both
513///   sides fused into one entity, which is precisely the outcome
514///   `entity::loader`'s caller exists to prevent. Git also writes
515///   conflict markers into frontmatter, so scanning it is not merely
516///   safe, it is required.
517pub fn has_merge_conflict_markers(text: &str) -> bool {
518    // One view, not two scans: a conflict can straddle the `---`
519    // terminator (git writes markers wherever the hunks fall), so the
520    // raw frontmatter and the masked body are rejoined and scanned as
521    // a single text. Masking preserves byte length, so the join is the
522    // original file with only body code blocks blanked.
523    let body = body_after_frontmatter(text);
524    let frontmatter = &text[..text.len() - body.len()];
525    let view = format!("{frontmatter}{}", mask_code_blocks(body));
526
527    let mut seen_start = false;
528    let mut seen_separator = false;
529    for line in view.lines() {
530        if line.starts_with("<<<<<<< ") {
531            seen_start = true;
532            seen_separator = false;
533        } else if seen_start && line.trim_end() == "=======" {
534            seen_separator = true;
535        } else if seen_separator && line.starts_with(">>>>>>> ") {
536            return true;
537        }
538    }
539    false
540}
541
542// ---------------------------------------------------------------------------
543// Section splitting
544// ---------------------------------------------------------------------------
545
546/// Tracks one schema-declared section key seen more than once on parse.
547/// `key` is the slugified storage key (e.g. `realization`); `heading` is
548/// the original literal text from the first occurrence (e.g. `Realization`).
549/// Sections keyed by derived key; each value is the heading line
550/// VERBATIM from the original body plus the section's content.
551pub(crate) type SplitSections = IndexMap<String, (String, String)>;
552
553/// `occurrences` counts every header line for that key — first plus
554/// duplicates.
555pub(crate) struct DuplicateSection {
556    pub key: String,
557    pub heading: String,
558    pub occurrences: usize,
559}
560
561/// The section boundary: a column-0 ATX `## ` line with a non-empty
562/// rest, matched over a MASKED text. One definition, used over the
563/// whole body and again over each piece the splitter reads from a
564/// neutral start.
565fn section_heading_re() -> &'static Regex {
566    static RE: OnceLock<Regex> = OnceLock::new();
567    RE.get_or_init(|| Regex::new(r"(?m)^## (.+)$").unwrap())
568}
569
570/// A section's stored content and the body offset where it starts.
571///
572/// Leading trim drops blank lines wholesale but keeps the first
573/// visible line's indentation: a full trim promoted an indented
574/// heading-lookalike (` ## Specifies`) to column 0 inside stored
575/// content, where the catch-all re-emit made the NEXT parse read
576/// it as a real section heading — structure from content, and a
577/// broken parse-generate fixpoint (fuzz finding, long tier,
578/// 2026-08-24, corpus member `crash-de0c69e0…`). Trailing trim
579/// stays full: it can never move a line to column 0. The
580/// runtime validator's embedded-heading guard keeps its own full
581/// trim, so the mutation path refuses exactly what it refused.
582fn section_content(body: &str, content_start: usize, content_end: usize) -> (&str, usize) {
583    let raw = &body[content_start..content_end];
584    let visible_start = raw
585        .split_inclusive('\n')
586        .take_while(|line| line.trim().is_empty())
587        .map(str::len)
588        .sum::<usize>();
589    (
590        raw[visible_start..].trim_end(),
591        content_start + visible_start,
592    )
593}
594
595/// Every section boundary of `body` in document order, each the byte
596/// range of its heading line.
597///
598/// The first pass is the regex over the masked body: a column-0 `## `
599/// line outside every code block. That pass reads each heading where
600/// it stands, and a heading can stand inside a block the referee is
601/// still reading: an HTML block of a kind no blank line ends (`<!X`,
602/// `<!--`, `<?`), or a table. The splitter does not narrow the
603/// boundary there (a `## ` line inside an unterminated comment stays a
604/// section, so a stray `<!--` never swallows the rest of the document),
605/// but the section's content was then read in situ under that block's
606/// context, and the generator writes every section from a neutral
607/// start: heading line, newline, content. Read from there the same
608/// bytes can mean something else. A `<!--` that was inert inside a
609/// `<!X` block opens a comment, the tilde fence after it goes dead, and
610/// a `## ` line the fence masked in situ reads as a heading on the next
611/// parse; the second parse splits where the first did not and the two
612/// generations differ (fuzz findings, CI runs 2026-09-08 and
613/// 2026-09-09, corpus members `crash-c9e7bbf7…` and `crash-ce631bf5…`;
614/// in the first the enclosing block was opened by the preceding
615/// section, in the second by the preamble before any heading, so no
616/// rule about closers between merged pieces can repair the class).
617///
618/// So the second pass reads every such section the way the generator
619/// will write it. A heading the referee did not itself read as a
620/// heading in situ was read inside some other block; its piece
621/// (verbatim heading line, newline, trimmed content) is masked from a
622/// neutral start, and the first `## ` line that surfaces becomes a
623/// boundary of its own. The new piece is read the same way, and so on
624/// until every piece shows exactly one boundary. Boundaries are only
625/// ever added, and only at lines the next parse would have split on
626/// anyway, so the first parse already lands on the fixpoint. A section
627/// whose heading the referee read as a heading stands in a neutral
628/// context already (a column-0 ATX heading ends every paragraph, list
629/// and quote before it, and a code block would have masked it), so its
630/// in-situ reading and the generator's agree; reading it again would
631/// find nothing, which is why the heading list is only a cost filter
632/// and most documents never enter the second pass.
633fn section_boundaries(body: &str, masked_body: &str) -> Vec<Range<usize>> {
634    let mut bounds: BTreeMap<usize, usize> = section_heading_re()
635        .find_iter(masked_body)
636        .map(|m| (m.start(), m.end()))
637        .collect();
638    if bounds.is_empty() {
639        return Vec::new();
640    }
641    let read_as_heading = crate::markdown::heading_starts(body);
642    let mut work: Vec<usize> = bounds
643        .keys()
644        .copied()
645        .filter(|start| read_as_heading.binary_search(start).is_err())
646        .collect();
647    while let Some(start) = work.pop() {
648        let end = bounds[&start];
649        let content_end = bounds
650            .range(start + 1..)
651            .next()
652            .map_or(body.len(), |(next, _)| *next);
653        let heading_line = &body[start..end];
654        let (content, content_start) = section_content(body, end, content_end);
655        let piece = format!("{heading_line}\n{content}");
656        let masked = mask_code_blocks(&piece);
657        let Some(extra) = section_heading_re()
658            .find_iter(&masked)
659            .find(|m| m.start() > 0)
660        else {
661            continue;
662        };
663        // The piece is heading line, `\n`, content: an offset past the
664        // heading line maps into the body at the content's start.
665        let abs_start = content_start + (extra.start() - heading_line.len() - 1);
666        bounds.insert(abs_start, abs_start + extra.len());
667        work.push(abs_start);
668    }
669    bounds.into_iter().map(|(start, end)| start..end).collect()
670}
671
672/// Split body into named sections. Returns `Map<lowercase_key,
673/// (heading_line, content)>` — the heading line VERBATIM from the
674/// original body, because the catch-all re-emits it and a heading
675/// rebuilt from the derived key changes what the CommonMark referee
676/// sees (a CR inside a heading is a line ending of its own, so its
677/// tail can be a live fence opener; the derived key lost the CRs, the
678/// re-parse un-masked the section's content, and a promoted empty
679/// heading then vanished — fuzz finding, corpus member
680/// `crash-9fd95247…`) — plus a list of duplicate-heading occurrences.
681/// Duplicate headings keep the first occurrence's body; subsequent
682/// occurrences are dropped from the storage value entirely (no
683/// embedded `## Heading` separator). The caller decides whether each
684/// duplicate becomes a `WarningHint` (schema-declared keys only —
685/// catch-all repetition stays silent). The third element is every
686/// literal heading text in document order (duplicates included) — the
687/// raw material for the health check that distinguishes "section
688/// absent" from "content under a non-deriving heading".
689pub(crate) fn split_sections(
690    body: &str,
691    masked_body: &str,
692) -> (SplitSections, Vec<DuplicateSection>, Vec<String>) {
693    // IndexMap, not HashMap: the catch-all builder re-emits non-schema
694    // sections in this map's iteration order, so the order must be the
695    // document's — hash-random order made canonical bytes unstable
696    // across parses whenever more than one non-schema section coexisted
697    // (reachable on the tolerant local-read path, which refuses nothing).
698    let mut sections = IndexMap::new();
699    let mut duplicates: HashMap<String, DuplicateSection> = HashMap::new();
700    let mut raw_headings = Vec::new();
701    let boundaries = section_boundaries(body, masked_body);
702
703    for (i, m) in boundaries.iter().enumerate() {
704        // Extract heading name from original body (not masked)
705        let heading_line = &body[m.clone()];
706        let name = heading_line
707            .strip_prefix("## ")
708            .unwrap_or(heading_line)
709            .trim();
710
711        let content_end = boundaries.get(i + 1).map_or(body.len(), |next| next.start);
712        let (content, _) = section_content(body, m.end, content_end);
713        let content = content.to_string();
714        // Schema section keys are underscore-separated (e.g. `current_state`).
715        // A heading like `## Current State` must derive to the same form so
716        // schema-declared sections land in `result_sections` under the right
717        // key instead of falling through to catch-all — which would break
718        // canonical byte-stability for any multi-word section. The derivation
719        // is shared with the schema loader's round-trip check — never inline
720        // a second copy here.
721        let key = memstead_schema::derive_section_key(name);
722        raw_headings.push(name.to_string());
723
724        match sections.entry(key.clone()) {
725            indexmap::map::Entry::Vacant(slot) => {
726                slot.insert((heading_line.to_string(), content));
727                duplicates.insert(
728                    key.clone(),
729                    DuplicateSection {
730                        key: key.clone(),
731                        heading: name.to_string(),
732                        occurrences: 1,
733                    },
734                );
735            }
736            indexmap::map::Entry::Occupied(_) => {
737                // First-wins: drop this duplicate's body entirely. Bump the
738                // occurrence count for the warning emitted by the caller.
739                if let Some(d) = duplicates.get_mut(&key) {
740                    d.occurrences += 1;
741                }
742            }
743        }
744    }
745
746    let dup_list: Vec<DuplicateSection> = duplicates
747        .into_values()
748        .filter(|d| d.occurrences > 1)
749        .collect();
750
751    (sections, dup_list, raw_headings)
752}
753
754/// Extract the title from the first `# ` heading.
755///
756/// Scans the masked body so a `# ` line inside a code block can never
757/// become the entity title, and reads the text back from the original —
758/// masking preserves byte offsets and line count, so the two line
759/// sequences correspond one-to-one.
760fn extract_title(body: &str, masked_body: &str) -> Option<String> {
761    for (line, masked) in body.lines().zip(masked_body.lines()) {
762        if masked.starts_with("# ") {
763            return Some(line[2..].trim().to_string());
764        }
765    }
766    None
767}
768
769// ---------------------------------------------------------------------------
770// Heading spans (H3–H6)
771// ---------------------------------------------------------------------------
772
773/// Extract H3–H6 heading spans from each section's content. Byte offsets are
774/// into the (trimmed) section string stored in `result_sections`. Code blocks
775/// are masked before scanning so `### foo` inside any code block is ignored.
776///
777/// End offsets use a level-aware closing rule: a span closes at the next
778/// heading with the same or lower level (H3 closes on next H3 or H2 — but
779/// H2 doesn't appear here since sections are already split), otherwise at
780/// the end of the section. Level skips (H2 → H4 without H3) are tolerated:
781/// the H4 span is recorded flat, and query-time path resolution uses offset
782/// containment to reconstruct ancestry.
783fn extract_heading_spans(sections: &IndexMap<String, String>) -> HashMap<String, Vec<HeadingSpan>> {
784    // Compiled once per process; shape-constrained so it can't fail at runtime.
785    static RE: OnceLock<Regex> = OnceLock::new();
786    let re = RE.get_or_init(|| Regex::new(r"(?m)^(#{3,6})[ \t]+(.+)$").unwrap());
787    let mut out: HashMap<String, Vec<HeadingSpan>> = HashMap::new();
788
789    for (key, content) in sections {
790        if content.is_empty() {
791            continue;
792        }
793        let masked = mask_code_blocks(content);
794
795        // Collect (start_offset, level, title) in document order.
796        let raw: Vec<(usize, u8, String)> = re
797            .captures_iter(&masked)
798            .map(|cap| {
799                let whole = cap.get(0).unwrap();
800                let level = cap[1].len() as u8; // 3..=6
801                // Read the title from the original (unmasked) content so the
802                // captured text survives code-block masking's space-padding.
803                let line_end = content[whole.start()..]
804                    .find('\n')
805                    .map(|i| whole.start() + i)
806                    .unwrap_or(content.len());
807                let hashes_end = whole.start() + level as usize;
808                let title = content[hashes_end..line_end].trim().to_string();
809                (whole.start(), level, title)
810            })
811            .collect();
812
813        if raw.is_empty() {
814            continue;
815        }
816
817        let mut spans: Vec<HeadingSpan> = Vec::with_capacity(raw.len());
818        for (i, &(start, level, ref title)) in raw.iter().enumerate() {
819            // Scan forward for the next heading with level <= this one.
820            let end = raw[i + 1..]
821                .iter()
822                .find(|(_, l, _)| *l <= level)
823                .map(|(s, _, _)| *s)
824                .unwrap_or(content.len());
825            spans.push(HeadingSpan {
826                level,
827                title: title.clone(),
828                start_offset: start,
829                end_offset: end,
830            });
831        }
832        out.insert(key.clone(), spans);
833    }
834
835    out
836}
837
838// ---------------------------------------------------------------------------
839// Catch-all section
840// ---------------------------------------------------------------------------
841
842/// Build catch-all section content from its own section + non-schema sections.
843fn build_catch_all(sections: &SplitSections, schema: &TypeDefinition) -> String {
844    let catch_all = match schema.catch_all_section() {
845        Some(s) => s,
846        None => return String::new(),
847    };
848
849    let known_sections: HashSet<&str> = schema
850        .sections
851        .iter()
852        .map(|s| s.key.as_str())
853        .chain(std::iter::once("relationships"))
854        .collect();
855
856    let mut parts = Vec::new();
857
858    // First, add the explicit catch-all section content
859    if let Some((_, content)) = sections.get(catch_all.key.as_str())
860        && !content.is_empty()
861    {
862        parts.push(content.clone());
863    }
864
865    // Then add all non-schema sections, each re-emitted under its
866    // ORIGINAL heading line, byte-verbatim — never a heading rebuilt
867    // from the derived key: the rebuilt form changed what the referee
868    // sees (a CR inside a heading is a CommonMark line ending of its
869    // own, so its tail can be a live fence opener the derived key
870    // lost), and the re-parse then promoted masked content to
871    // structure (fuzz finding, corpus member `crash-9fd95247…`).
872    // Document order — `sections` is an IndexMap for exactly this
873    // loop: with more than one non-schema section (reachable on the
874    // tolerant local-read path, which refuses nothing) a hash-random
875    // order made the reconstructed catch-all differ from parse to parse.
876    for (key, (heading_line, content)) in sections {
877        if !known_sections.contains(key.as_str()) && !content.is_empty() {
878            parts.push(format!("{heading_line}\n{content}"));
879        }
880    }
881
882    // Incremental context close: every close decision is judged over
883    // the RUNNING string after each append — never over a piece in
884    // isolation. Isolation misjudges in both directions (lazy
885    // continuation and CR line endings make the same bytes a fence in
886    // one context and prose in another): an isolation close injected a
887    // spurious closer that the generator's part-level close then paired
888    // into an empty fence block, growing the document every round
889    // (corpus candidate `crash-619fe90c`), while skipping the close
890    // entirely let a piece's dangling fence swallow the next piece's
891    // heading (corpus member `crash-07c152bb`). Closing in context
892    // after each piece keeps both: a dangling fence closes before the
893    // next piece, and no closer is ever added for a construct the
894    // document context does not read as a fence. The oracle verifies
895    // its closer against the mask, so the appended line is a real
896    // closer wherever it lands. The context is not only fences: an
897    // HTML block of the kinds no blank line ends (`<!X`, `<!--`, `<?`,
898    // `<![CDATA[`, a `<script>`-family tag) hides every fence the
899    // referee would otherwise read, so a piece that ends inside one
900    // changes what the NEXT piece's fences mean — a `## ` line that a
901    // fence masked in situ surfaces as a heading after the merge, and
902    // as an empty non-schema section it is dropped a round later
903    // (fuzz finding, long tier, 0.17.0 release readiness run, corpus
904    // member `crash-1233c134…`). The same oracle closes both.
905    //
906    // A closer between two pieces is always safe to write: every piece
907    // reads as exactly one section from a neutral start
908    // (`section_boundaries` guarantees it, reading each section the
909    // way it is written here), and the verified closer leaves exactly
910    // that start for the next piece. The mirror case, a closer that
911    // changed how the next piece read because that piece had been read
912    // inside a block the previous one left open, is settled at the
913    // splitter, not judged here (fuzz findings, corpus members
914    // `crash-c9e7bbf7…` and `crash-ce631bf5…`).
915    let mut joined = String::new();
916    for piece in parts {
917        if joined.is_empty() {
918            joined = piece;
919        } else {
920            joined.push_str("\n\n");
921            joined.push_str(&piece);
922        }
923        if let Some(closer) = crate::markdown::closing_context_if_unterminated(&joined) {
924            joined.push('\n');
925            joined.push_str(&closer);
926        }
927    }
928    joined
929}
930
931// ---------------------------------------------------------------------------
932// Relationships
933// ---------------------------------------------------------------------------
934
935/// Parse typed relationships from the Relationships section.
936///
937/// Recognises two row shapes:
938/// - simple: `- **TYPE**: [[target]]` → `description: None`
939/// - em-dash: `- **TYPE**: [[target]] — text` → `description: Some(text)`
940///
941/// Returns the relations plus parse-time warnings flagging
942/// AMBIGUOUS-delimiter rows (`-- text`, `- text`, en-dash, minus). On
943/// AMBIGUOUS rows the description is dropped — the renderer will
944/// normalise the row to the simple form on next write.
945///
946/// Rows inside a code block are not relationships. The scan runs over
947/// the masked section body and reads every captured span from the
948/// original, so a fenced or indented example of the row syntax — the
949/// obvious thing to write in an entity documenting that syntax — no
950/// longer becomes a live edge and an auto-stub. Without the mask this
951/// path synthesised edges from links the strict validator cannot see
952/// (`validator::strict::check_wiki_links` masks), which is exactly the
953/// asymmetry the one-definition rule exists to prevent.
954pub(crate) fn parse_relationships_with_warnings(
955    text: &str,
956    mem: &str,
957    entity_id: Option<&EntityId>,
958) -> (Vec<Relationship>, Vec<crate::ops::WarningHint>) {
959    // Anchor on the canonical row prefix `- **TYPE**: [[<target>]]` and
960    // capture everything that follows on the same line so the trailing
961    // segment can be classified (simple, em-dash, or AMBIGUOUS).
962    //
963    // The target must not cross a line: a ROW is a line. A capture
964    // spanning a newline only ever came from degenerate drift, and it
965    // cannot round-trip — the generated multi-line token re-enters the
966    // mask with different structure (a following `-` + tab line reads
967    // as list-item indented code and swallows the closing `]]`), so
968    // the row silently vanished one round later (fuzz finding, corpus
969    // member `crash-93f0a4bd…`). Ids containing newlines can never
970    // exist as entity files, so such pseudo-rows are consistently not
971    // relationships in ANY round.
972    static RE: OnceLock<Regex> = OnceLock::new();
973    let re = RE.get_or_init(|| {
974        Regex::new(r"(?m)^\s*-\s*\*\*(\w+)\*\*:\s*\[\[([^\]\n]+)\]\](?P<tail>[^\n]*)").unwrap()
975    });
976    let mut relationships = Vec::new();
977    let mut warnings = Vec::new();
978    // Blocks AND inline spans — the same mask every link scanner uses.
979    // A legitimate row's target can never sit inside a code span, so
980    // masking spans costs nothing and closes the seam: with a
981    // blocks-only mask a row inside a multi-line inline span stayed
982    // invisible to the validator and to every extractor while still
983    // building an edge and a stub. Masking preserves byte offsets, so a
984    // match found in the masked copy indexes the original exactly.
985    let masked = mask_code_blocks_and_spans(text);
986    for cap in re.captures_iter(&masked) {
987        let rel_type = text[cap.get(1).unwrap().range()].to_uppercase();
988        // Read-time parsing of the ## Relationships table tolerates
989        // pre-strict on-disk drift so legacy rows whose target fails
990        // the wiki-link grammar continue to round-trip. The mutation
991        // pipeline (`memstead_relate`, declare_relations) gates strictly
992        // via `validate_relation_target_grammar`.
993        let target = wiki_link_to_id_lenient(&text[cap.get(2).unwrap().range()], mem);
994        // A raw target that decodes to an EMPTY path (`[[specs--]]`
995        // after the self-prefix strip, `[[../]]` after decoration
996        // stripping) is not a relationship: the generator would render
997        // it as `[[]]`, which the row pattern cannot re-capture, so the
998        // row silently vanished one round later (fuzz finding, corpus
999        // member `crash-0c7207a1…`). Skipping it here mirrors how rows
1000        // that never match the pattern behave; both strict gates refuse
1001        // such targets outright.
1002        if target.path().is_empty() {
1003            continue;
1004        }
1005        let tail = cap.name("tail").map(|m| &text[m.range()]).unwrap_or("");
1006        let description = match classify_description_tail(tail) {
1007            DescriptionTail::None => None,
1008            DescriptionTail::EmDash(text) => Some(text),
1009            DescriptionTail::Ambiguous(literal) => {
1010                if let Some(id) = entity_id {
1011                    warnings.push(crate::ops::WarningHint::AmbiguousDescriptionDelimiter {
1012                        from: id.clone(),
1013                        rel_type: rel_type.clone(),
1014                        target: target.clone(),
1015                        trailing: literal,
1016                    });
1017                }
1018                None
1019            }
1020        };
1021        relationships.push(Relationship {
1022            rel_type,
1023            target,
1024            description,
1025        });
1026    }
1027    (relationships, warnings)
1028}
1029
1030/// Classification of the per-line tail that follows `]]` on a
1031/// `## Relationships` row.
1032enum DescriptionTail {
1033    /// Tail is empty or whitespace-only.
1034    None,
1035    /// Tail begins with the canonical em-dash delimiter; carries the
1036    /// captured description text (trimmed of trailing whitespace).
1037    EmDash(String),
1038    /// Tail starts with a non-canonical dash-like delimiter (`-`,
1039    /// `--`, U+2013 en-dash, U+2212 minus). Carries the literal
1040    /// trailing content so the warning surfaces what was dropped.
1041    Ambiguous(String),
1042}
1043
1044/// Inspect the post-`]]` tail of a `## Relationships` row and decide
1045/// what shape it takes. The em-dash delimiter is the exact three-byte
1046/// UTF-8 sequence of U+2014 framed by single ASCII spaces; everything
1047/// else falls into [`DescriptionTail::None`] or
1048/// [`DescriptionTail::Ambiguous`].
1049fn classify_description_tail(tail: &str) -> DescriptionTail {
1050    let trimmed_end = tail.trim_end();
1051    if trimmed_end.is_empty() {
1052        return DescriptionTail::None;
1053    }
1054    // Canonical: literal space + U+2014 + literal space + content.
1055    if let Some(rest) = trimmed_end.strip_prefix(" \u{2014} ") {
1056        if rest.is_empty() {
1057            return DescriptionTail::None;
1058        }
1059        return DescriptionTail::EmDash(rest.to_string());
1060    }
1061    // U+2014 directly after `]]` (no leading space) is also ambiguous
1062    // — the canonical form requires the framing space. Likewise an
1063    // em-dash with no trailing content (` — `) collapses to None.
1064    if let Some(rest) = trimmed_end.strip_prefix(" \u{2014}") {
1065        // ` —` (no trailing space, but content followed) lands here.
1066        return DescriptionTail::Ambiguous(format!(" \u{2014}{rest}"));
1067    }
1068    // Dash-likes: ASCII `--`, ASCII `-`, en-dash U+2013, minus U+2212.
1069    let starters = [" --", " -", " \u{2013}", " \u{2212}"];
1070    if starters
1071        .iter()
1072        .any(|prefix| trimmed_end.starts_with(prefix))
1073    {
1074        return DescriptionTail::Ambiguous(trimmed_end.to_string());
1075    }
1076    // Anything else after `]]` (e.g. inline comment, stray text) —
1077    // classify as ambiguous so the operator sees that content was
1078    // dropped rather than silently swallowed.
1079    DescriptionTail::Ambiguous(trimmed_end.to_string())
1080}
1081
1082// ---------------------------------------------------------------------------
1083// Wiki-links
1084// ---------------------------------------------------------------------------
1085
1086/// The `[[target]]` / `[[target|label]]` wiki-link pattern, compiled once.
1087///
1088/// The inner group is `*`, not `+`, so an empty target `[[]]` is *seen*
1089/// by every path — the strict validator refuses it with a typed
1090/// `InvalidWikiLink`, and this module's strict extractor routes it to
1091/// the same refusal. A pattern that cannot see `[[]]` is how one path
1092/// came to silently ignore what another path refused.
1093fn wiki_link_re() -> &'static Regex {
1094    static RE: OnceLock<Regex> = OnceLock::new();
1095    RE.get_or_init(|| Regex::new(r"\[\[([^\]]*)\]\]").unwrap())
1096}
1097
1098/// Extract unique mem-prefixed entity IDs from inline wiki-links,
1099/// strictly validating each target against the slug-form grammar.
1100/// Strips code blocks and inline code spans before scanning, by the
1101/// one CommonMark definition ([`crate::markdown`]).
1102///
1103/// Returns the deduped valid ids on success, or every refusal in the
1104/// scan window on failure (errors are collected, not fail-fast — the
1105/// agent sees every malformed link in a single round-trip).
1106///
1107/// Mutation-pipeline callers (`synthesise_alias_relations`, etc.) use
1108/// this strict variant and map [`WikiLinkError`] to the typed engine
1109/// envelope with section context. Read-side scanners that must
1110/// tolerate pre-strict on-disk drift use [`extract_inline_links_lenient`].
1111pub(crate) fn extract_inline_links(
1112    text: &str,
1113    mem: &str,
1114) -> Result<Vec<EntityId>, Vec<WikiLinkError>> {
1115    let stripped = mask_code_blocks_and_spans(text);
1116
1117    let link_re = wiki_link_re();
1118    let mut seen = HashSet::new();
1119    let mut links = Vec::new();
1120    let mut errors = Vec::new();
1121
1122    for cap in link_re.captures_iter(&stripped) {
1123        match wiki_link_to_id(&cap[1], mem) {
1124            Ok(id) => {
1125                if errors.is_empty() && seen.insert(id.0.clone()) {
1126                    links.push(id);
1127                }
1128            }
1129            Err(e) => errors.push(e),
1130        }
1131    }
1132
1133    if errors.is_empty() {
1134        Ok(links)
1135    } else {
1136        Err(errors)
1137    }
1138}
1139
1140/// Permissive sibling of [`extract_inline_links`] for read-side
1141/// scanners. Decodes every `[[...]]` token via [`wiki_link_to_id_lenient`]
1142/// so on-disk drift (legacy entities, archive-imports from pre-strict
1143/// engines, partial-mutation rollbacks) keeps flowing through dangling-
1144/// link reporters and graph inspectors. Mutation paths MUST NOT use this
1145/// helper — see [`extract_inline_links`] for the strict variant.
1146pub fn extract_inline_links_lenient(text: &str, mem: &str) -> Vec<EntityId> {
1147    let stripped = mask_code_blocks_and_spans(text);
1148
1149    let link_re = wiki_link_re();
1150    let mut seen = HashSet::new();
1151    let mut links = Vec::new();
1152
1153    for cap in link_re.captures_iter(&stripped) {
1154        // An empty target decodes to no id. The read side tolerates
1155        // drift by ignoring what it cannot decode; the strict side
1156        // refuses it (`extract_inline_links`). Both *see* it — that is
1157        // the part that must not diverge.
1158        if cap[1].is_empty() {
1159            continue;
1160        }
1161        let id = wiki_link_to_id_lenient(&cap[1], mem);
1162        if seen.insert(id.0.clone()) {
1163            links.push(id);
1164        }
1165    }
1166
1167    links
1168}
1169
1170// ---------------------------------------------------------------------------
1171// Content hash
1172// ---------------------------------------------------------------------------
1173
1174/// Compute SHA-256 hash of content, truncated to 16 hex characters.
1175pub fn compute_hash(content: &str) -> String {
1176    let mut hasher = Sha256::new();
1177    hasher.update(content.as_bytes());
1178    let result = hasher.finalize();
1179    crate::hex_lower(&result)[..16].to_string()
1180}
1181
1182// ---------------------------------------------------------------------------
1183// Errors
1184// ---------------------------------------------------------------------------
1185
1186#[derive(Debug, thiserror::Error)]
1187pub enum ParseError {
1188    #[error("missing frontmatter")]
1189    MissingFrontmatter,
1190    #[error("invalid frontmatter: {0}")]
1191    InvalidFrontmatter(String),
1192    #[error("missing title")]
1193    MissingTitle,
1194    #[error("io error: {0}")]
1195    Io(#[from] std::io::Error),
1196}
1197
1198/// End-to-end pins for the six verified code-block misparse classes,
1199/// on the real entity paths: section splitting, title extraction,
1200/// heading spans, and wiki-link extraction. The unit-level pins for
1201/// the mask itself live in [`crate::markdown`]; these assert the
1202/// classes are actually fixed where they did damage.
1203#[cfg(test)]
1204mod commonmark_referee;
1205
1206#[cfg(test)]
1207mod tests;