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#[cfg(test)]
1199mod tests {
1200    use super::*;
1201    use memstead_schema::{builtin_names, type_by_name};
1202    use std::sync::Arc;
1203
1204    fn spec_schema() -> Arc<TypeDefinition> {
1205        type_by_name(builtin_names::SPEC).unwrap()
1206    }
1207
1208    fn memo_schema() -> Arc<TypeDefinition> {
1209        type_by_name(builtin_names::MEMO).unwrap()
1210    }
1211
1212    #[test]
1213    fn parse_metadata_types() {
1214        let meta = parse_metadata("key: value\nnum: 42\nfloat: 0.85\nbool: true\nfalsy: false");
1215        assert_eq!(meta["key"], MetadataValue::String("value".to_string()));
1216        assert_eq!(meta["num"], MetadataValue::Integer(42));
1217        assert_eq!(meta["float"], MetadataValue::Float(0.85));
1218        assert_eq!(meta["bool"], MetadataValue::Bool(true));
1219        assert_eq!(meta["falsy"], MetadataValue::Bool(false));
1220    }
1221
1222    #[test]
1223    fn parse_metadata_strips_comments() {
1224        let meta = parse_metadata("key: value # this is a comment");
1225        assert_eq!(meta["key"], MetadataValue::String("value".to_string()));
1226    }
1227
1228    #[test]
1229    fn parse_metadata_strips_quotes() {
1230        let meta = parse_metadata("key: \"quoted value\"\nkey2: 'single'");
1231        assert_eq!(
1232            meta["key"],
1233            MetadataValue::String("quoted value".to_string())
1234        );
1235        assert_eq!(meta["key2"], MetadataValue::String("single".to_string()));
1236    }
1237
1238    #[test]
1239    fn parse_metadata_survives_malformed_values() {
1240        // A lone quote character satisfies both starts_with and ends_with —
1241        // the old unguarded slice `s[1..s.len()-1]` panicked on it.
1242        let meta = parse_metadata(
1243            "key: \"\nkey2: '\nkey3: \"\"\nkey4: ''\nkey5: \"unterminated\nkey6: mixed'\"",
1244        );
1245        assert_eq!(meta["key"], MetadataValue::String("\"".to_string()));
1246        assert_eq!(meta["key2"], MetadataValue::String("'".to_string()));
1247        assert_eq!(meta["key3"], MetadataValue::String(String::new()));
1248        assert_eq!(meta["key4"], MetadataValue::String(String::new()));
1249        assert_eq!(
1250            meta["key5"],
1251            MetadataValue::String("\"unterminated".to_string())
1252        );
1253        assert_eq!(meta["key6"], MetadataValue::String("mixed'\"".to_string()));
1254
1255        // More frontmatter shapes that must parse to a value, never panic:
1256        // colon-only lines, multi-byte values, keyless colons, huge digits.
1257        let meta =
1258            parse_metadata(":\n: value\nkey7: ✓\"\nkey8: 99999999999999999999999999\nkey9: -");
1259        assert_eq!(meta["key7"], MetadataValue::String("✓\"".to_string()));
1260        assert_eq!(
1261            meta["key8"],
1262            MetadataValue::String("99999999999999999999999999".to_string())
1263        );
1264        assert_eq!(meta["key9"], MetadataValue::String("-".to_string()));
1265    }
1266
1267    #[test]
1268    fn parse_metadata_skips_comments_and_empty() {
1269        let meta = parse_metadata("# comment\n\nkey: val\n---");
1270        assert_eq!(meta.len(), 1);
1271        assert_eq!(meta["key"], MetadataValue::String("val".to_string()));
1272    }
1273
1274    #[test]
1275    fn peek_type_finds_value() {
1276        let content = "---\ntype: memo\ntitle: Test\n---\n# Body\n";
1277        assert_eq!(
1278            peek_type_from_frontmatter(content),
1279            Some("memo".to_string())
1280        );
1281    }
1282
1283    #[test]
1284    fn peek_type_returns_none_when_missing() {
1285        let content = "---\ntitle: Test\n---\n# Body\n";
1286        assert_eq!(peek_type_from_frontmatter(content), None);
1287    }
1288
1289    #[test]
1290    fn peek_type_returns_none_without_frontmatter() {
1291        let content = "# Just a heading\n\nBody with type: concept inside text.\n";
1292        assert_eq!(peek_type_from_frontmatter(content), None);
1293    }
1294
1295    /// The contract on a carriage-return document: the opening fence is
1296    /// five bytes, the meta slice carries no fence, and the body starts
1297    /// after the closing fence's `\r\n` — the shape the CR-blind site of
1298    /// the 2026-09-04 census got wrong with a four-byte offset constant.
1299    #[test]
1300    fn split_core_crlf_document_borrows_meta_and_body() {
1301        let content = "---\r\ntype: spec\r\nlevel: M0\r\n---\r\n# Title\r\n\r\nBody.\r\n";
1302        let (stripped, split) = split_frontmatter_core(content);
1303        assert_eq!(stripped, content);
1304        assert_eq!(
1305            split,
1306            Frontmatter::Present {
1307                meta: "type: spec\r\nlevel: M0\r",
1308                body: "# Title\r\n\r\nBody.\r\n"
1309            }
1310        );
1311        let (meta, body) = frontmatter_parts(content).unwrap();
1312        assert_eq!(meta, "type: spec\r\nlevel: M0\r");
1313        assert_eq!(body, "# Title\r\n\r\nBody.\r\n");
1314        assert_eq!(body_after_frontmatter(content), body);
1315        // The same document with a byte-order mark splits identically.
1316        let marked = format!("\u{feff}{content}");
1317        assert_eq!(frontmatter_parts(&marked), Some((meta, body)));
1318    }
1319
1320    /// A fence anywhere but the first line is not frontmatter: the whole
1321    /// document is body, and nothing is injected or stripped at the first
1322    /// fence found — the shape the fence-searching site of the census got
1323    /// wrong.
1324    #[test]
1325    fn first_fence_not_at_document_start_is_no_frontmatter() {
1326        let content = "# Intro\n\n---\ntype: spec\n---\n\nBody.\n";
1327        assert_eq!(
1328            split_frontmatter_core(content),
1329            (content, Frontmatter::NoOpeningDelimiter)
1330        );
1331        assert_eq!(frontmatter_parts(content), None);
1332        assert_eq!(body_after_frontmatter(content), content);
1333        assert_eq!(peek_type_from_frontmatter(content), None);
1334        // An opening fence that never closes is not frontmatter either.
1335        let unclosed = "---\ntype: spec\nno close\n";
1336        assert_eq!(
1337            split_frontmatter_core(unclosed),
1338            (unclosed, Frontmatter::Unclosed)
1339        );
1340        assert_eq!(frontmatter_parts(unclosed), None);
1341    }
1342
1343    #[test]
1344    fn peek_type_handles_windows_line_endings() {
1345        let content = "---\r\ntype: principle\r\n---\r\n# Body\r\n";
1346        assert_eq!(
1347            peek_type_from_frontmatter(content),
1348            Some("principle".to_string())
1349        );
1350    }
1351
1352    #[test]
1353    fn peek_type_strips_quotes_and_comments() {
1354        let quoted = "---\ntype: \"concept\"\n---\n";
1355        assert_eq!(
1356            peek_type_from_frontmatter(quoted),
1357            Some("concept".to_string())
1358        );
1359        let commented = "---\ntype: memo # kind of\n---\n";
1360        assert_eq!(
1361            peek_type_from_frontmatter(commented),
1362            Some("memo".to_string())
1363        );
1364    }
1365
1366    #[test]
1367    fn peek_type_empty_value_returns_none() {
1368        let content = "---\ntype:\n---\n";
1369        assert_eq!(peek_type_from_frontmatter(content), None);
1370    }
1371
1372    #[test]
1373    fn peek_type_ignores_legacy_schema_key() {
1374        // After the hard break, a bare `schema:` in frontmatter is not
1375        // recognized as the type key — it's just arbitrary metadata.
1376        let content = concat!("---\n", "schema", ": memo\n---\n");
1377        assert_eq!(peek_type_from_frontmatter(content), None);
1378    }
1379
1380    #[test]
1381    fn mask_code_blocks_basic() {
1382        let input = "before\n```\ncode [[link]]\n```\nafter";
1383        let masked = mask_code_blocks(input);
1384        assert!(!masked.contains("[[link]]"));
1385        assert!(masked.contains("before"));
1386        assert!(masked.contains("after"));
1387    }
1388
1389    #[test]
1390    fn mask_code_blocks_preserves_line_count() {
1391        let input = "line1\n```\ncode\nmore code\n```\nline6";
1392        let masked = mask_code_blocks(input);
1393        assert_eq!(input.lines().count(), masked.lines().count());
1394    }
1395
1396    #[test]
1397    fn mask_code_blocks_unclosed() {
1398        let input = "before\n```\ncode\nmore code";
1399        let masked = mask_code_blocks(input);
1400        assert!(masked.contains("before"));
1401        assert!(!masked.contains("code"));
1402    }
1403
1404    #[test]
1405    fn parse_relationships_basic() {
1406        let text = "- **USES**: [[target-entity]]\n- **PART_OF**: [[parent]]";
1407        let rels = parse_relationships_with_warnings(text, "specs", None).0;
1408        assert_eq!(rels.len(), 2);
1409        assert_eq!(rels[0].rel_type, "USES");
1410        assert_eq!(rels[0].target.0, "specs--target-entity");
1411        assert_eq!(rels[1].rel_type, "PART_OF");
1412        assert_eq!(rels[1].target.0, "specs--parent");
1413        // Simple form parses without a description.
1414        assert!(rels[0].description.is_none());
1415        assert!(rels[1].description.is_none());
1416    }
1417
1418    #[test]
1419    fn parse_relationships_canonical_em_dash_captures_description() {
1420        let text = "- **OTHER**: [[a]] \u{2014} replaced by checkout-flow";
1421        let (rels, warnings) = parse_relationships_with_warnings(text, "specs", None);
1422        assert_eq!(rels.len(), 1);
1423        assert_eq!(
1424            rels[0].description.as_deref(),
1425            Some("replaced by checkout-flow")
1426        );
1427        assert!(warnings.is_empty(), "canonical em-dash does not warn");
1428    }
1429
1430    #[test]
1431    fn parse_relationships_em_dash_inside_description_body() {
1432        let text = "- **OTHER**: [[a]] \u{2014} note with — inside body";
1433        let (rels, warnings) = parse_relationships_with_warnings(text, "specs", None);
1434        assert_eq!(rels.len(), 1);
1435        assert_eq!(
1436            rels[0].description.as_deref(),
1437            Some("note with — inside body"),
1438            "the parser captures up to end-of-line; em-dashes inside the body survive"
1439        );
1440        assert!(warnings.is_empty());
1441    }
1442
1443    #[test]
1444    fn parse_relationships_ambiguous_double_hyphen_warns_and_drops_content() {
1445        let text = "- **USES**: [[a]] -- legacy delimiter";
1446        let entity_id = EntityId::new("specs", "src");
1447        let (rels, warnings) = parse_relationships_with_warnings(text, "specs", Some(&entity_id));
1448        assert_eq!(rels.len(), 1);
1449        assert!(rels[0].description.is_none(), "trailing content is dropped");
1450        assert_eq!(warnings.len(), 1);
1451        assert!(matches!(
1452            warnings[0],
1453            crate::ops::WarningHint::AmbiguousDescriptionDelimiter { .. }
1454        ));
1455    }
1456
1457    #[test]
1458    fn parse_relationships_ambiguous_single_hyphen_warns_and_drops_content() {
1459        let text = "- **USES**: [[a]] - single hyphen";
1460        let entity_id = EntityId::new("specs", "src");
1461        let (rels, warnings) = parse_relationships_with_warnings(text, "specs", Some(&entity_id));
1462        assert_eq!(rels.len(), 1);
1463        assert!(rels[0].description.is_none());
1464        assert_eq!(warnings.len(), 1);
1465        assert_eq!(warnings[0].code(), "AMBIGUOUS_DESCRIPTION_DELIMITER");
1466    }
1467
1468    #[test]
1469    fn parse_relationships_hyphenated_slug_target_parses_unambiguously() {
1470        let text = "- **USES**: [[some-slug-with-hyphens]] \u{2014} ok";
1471        let (rels, warnings) = parse_relationships_with_warnings(text, "specs", None);
1472        assert_eq!(rels.len(), 1);
1473        assert_eq!(rels[0].target.path(), "some-slug-with-hyphens");
1474        assert_eq!(rels[0].description.as_deref(), Some("ok"));
1475        assert!(warnings.is_empty());
1476    }
1477
1478    #[test]
1479    fn parse_full_entity() {
1480        let md = "\
1481---
1482type: spec
1483created_date: 2026-01-15
1484last_modified: 2026-04-12
1485level: M0
1486tags: backend, api
1487---
1488# Test Entity
1489
1490## Identity
1491
1492This is a test entity.
1493
1494## Purpose
1495
1496Testing the parser.
1497
1498## Relationships
1499
1500- **USES**: [[other-entity]]
1501
1502## Specifies
1503
1504Some specification content with [[inline-link]].
1505";
1506        let result = parse_markdown(md, "test-entity.md", &spec_schema(), "specs").unwrap();
1507        let entity = &result.entity;
1508        assert_eq!(entity.id.0, "specs--test-entity");
1509        assert_eq!(entity.title, "Test Entity");
1510        assert_eq!(entity.mem, "specs");
1511        assert_eq!(
1512            entity.metadata["type"],
1513            MetadataValue::String("spec".to_string())
1514        );
1515        assert_eq!(
1516            entity.metadata["level"],
1517            MetadataValue::String("M0".to_string())
1518        );
1519        assert_eq!(
1520            entity.metadata["tags"],
1521            MetadataValue::String("backend, api".to_string())
1522        );
1523        assert_eq!(entity.sections["identity"], "This is a test entity.");
1524        assert_eq!(entity.sections["purpose"], "Testing the parser.");
1525        assert_eq!(entity.relationships.len(), 1);
1526        assert_eq!(entity.relationships[0].rel_type, "USES");
1527        assert_eq!(entity.relationships[0].target.0, "specs--other-entity");
1528        assert_eq!(result.inline_links.len(), 1);
1529        assert_eq!(result.inline_links[0].0, "specs--inline-link");
1530    }
1531
1532    #[test]
1533    fn parse_full_entity_memo_schema() {
1534        let md = "\
1535---
1536type: memo
1537created_date: 2026-01-15
1538last_modified: 2026-04-12
1539status: active
1540tags: decision, architecture
1541---
1542# Use Sled For Storage
1543
1544## Claim
1545
1546Sled is the right embedded store for this workload.
1547
1548## Context
1549
1550We evaluated sled, rocksdb, and sqlite for the in-process graph cache.
1551
1552## Substance
1553
1554Sled wins on pure-Rust dependency footprint.
1555";
1556        let result = parse_markdown(md, "use-sled.md", &memo_schema(), "memos").unwrap();
1557        let entity = &result.entity;
1558        assert_eq!(entity.id.0, "memos--use-sled");
1559        assert_eq!(entity.title, "Use Sled For Storage");
1560        assert_eq!(entity.mem, "memos");
1561        assert_eq!(
1562            entity.metadata["type"],
1563            MetadataValue::String("memo".to_string())
1564        );
1565        assert_eq!(
1566            entity.metadata["status"],
1567            MetadataValue::String("active".to_string())
1568        );
1569        assert_eq!(
1570            entity.sections["claim"],
1571            "Sled is the right embedded store for this workload."
1572        );
1573        assert_eq!(
1574            entity.sections["context"],
1575            "We evaluated sled, rocksdb, and sqlite for the in-process graph cache."
1576        );
1577        assert_eq!(
1578            entity.sections["substance"],
1579            "Sled wins on pure-Rust dependency footprint."
1580        );
1581        assert!(!entity.sections.contains_key("identity"));
1582        assert!(!entity.sections.contains_key("purpose"));
1583    }
1584
1585    #[test]
1586    fn parse_entity_without_frontmatter() {
1587        let md = "# No Frontmatter\n\n## Identity\n\nJust a title and section.";
1588        let result = parse_markdown(md, "no-fm.md", &spec_schema(), "specs").unwrap();
1589        assert_eq!(result.entity.title, "No Frontmatter");
1590        // Only the auto-injected type field should be present
1591        assert_eq!(result.entity.metadata.len(), 1);
1592        assert_eq!(
1593            result.entity.metadata.get("type"),
1594            Some(&MetadataValue::String("spec".to_string()))
1595        );
1596    }
1597
1598    #[test]
1599    fn parse_entity_code_blocks_not_detected() {
1600        let md = "\
1601---
1602type: spec
1603---
1604# Code Test
1605
1606## Identity
1607
1608Test entity.
1609
1610## Specifies
1611
1612```
1613## Not A Section
1614- **USES**: [[not-a-link]]
1615```
1616
1617Real content after code block.
1618";
1619        let result = parse_markdown(md, "code-test.md", &spec_schema(), "specs").unwrap();
1620        // The ## inside code block should NOT be parsed as a section
1621        assert!(!result.entity.sections.contains_key("not a section"));
1622        // The wiki-link inside code block should NOT be extracted
1623        assert!(result.inline_links.is_empty());
1624    }
1625
1626    // Fixture pinned by the adversarial harness (seed 0x5eedf001, case 224):
1627    // a BOM'd file parsed tolerantly as all-body, losing its entire
1628    // frontmatter, while the strict validator and the archive path stripped
1629    // the mark and saw it. That divergence is why the mark is now stripped in
1630    // `split_frontmatter_core` and nowhere else: one implementation cannot
1631    // disagree with itself about where a document begins.
1632    #[test]
1633    fn bom_prefixed_frontmatter_is_recognized() {
1634        let md = "\u{feff}---\ntype: spec\n---\n# Bom Entity\n\n## Identity\n\nBody.\n";
1635        assert_eq!(peek_type_from_frontmatter(md), Some("spec".to_string()));
1636        assert_eq!(
1637            body_after_frontmatter(md),
1638            "# Bom Entity\n\n## Identity\n\nBody.\n"
1639        );
1640        let (meta, body) = split_frontmatter(md).unwrap();
1641        assert_eq!(meta, "type: spec");
1642        assert_eq!(body, "# Bom Entity\n\n## Identity\n\nBody.\n");
1643        let result = parse_markdown(md, "bom.md", &spec_schema(), "specs").unwrap();
1644        assert_eq!(
1645            result.entity.metadata["type"],
1646            MetadataValue::String("spec".to_string())
1647        );
1648        assert_eq!(result.entity.sections["identity"], "Body.");
1649    }
1650
1651    // Fixture pinned by the adversarial harness (seed 0x5eedf001, case 46):
1652    // a section whose content ends inside an open code fence absorbed every
1653    // section the generator wrote after it on the next parse — content
1654    // shifted between sections and the document GREW on every
1655    // parse→generate round. The generator now terminates the open fence;
1656    // the first round normalises, then parse→generate is a fixpoint.
1657    #[test]
1658    fn open_fence_in_section_content_does_not_swallow_following_sections() {
1659        let md = "\
1660---
1661type: spec
1662---
1663# Code Test
1664
1665## Identity
1666
1667Base.
1668
1669## Specifies
1670
1671```
1672truncated code with no closer";
1673        let schema = spec_schema();
1674        let e1 = parse_markdown(md, "open-fence.md", &schema, "specs").unwrap();
1675        let m1 = crate::entity::generator::generate_markdown(&e1.entity, &schema);
1676        let e2 = parse_markdown(&m1, "open-fence.md", &schema, "specs").unwrap();
1677        assert_eq!(
1678            e2.entity.sections["identity"], "Base.",
1679            "sections before the open fence survive"
1680        );
1681        assert!(
1682            !e2.entity.sections["specifies"].contains("## Constraints"),
1683            "the generated sections after the fence are not absorbed into it"
1684        );
1685        let m2 = crate::entity::generator::generate_markdown(&e2.entity, &schema);
1686        assert_eq!(
1687            m1, m2,
1688            "parse→generate is a fixpoint after one normalising round"
1689        );
1690    }
1691
1692    // Fixture pinned by the adversarial harness (seed 0x5eedf001, case 26):
1693    // a document carrying MULTIPLE non-schema sections — reachable on the
1694    // tolerant local-read path, which refuses nothing — reconstructed its
1695    // catch-all in HashMap iteration order, so canonical bytes differed
1696    // from parse to parse of the same input. The catch-all must re-emit
1697    // non-schema sections in document order, and parse→generate must be
1698    // idempotent for such input.
1699    #[test]
1700    fn catch_all_reconstruction_is_document_ordered_and_idempotent() {
1701        let md = "\
1702---
1703type: spec
1704---
1705# Multi Unknown
1706
1707## Identity
1708
1709Base.
1710
1711## Claim
1712
1713First unknown.
1714
1715## Context
1716
1717Second unknown.
1718
1719## Substance
1720
1721Third unknown.
1722";
1723        let schema = spec_schema();
1724        let e1 = parse_markdown(md, "multi-unknown.md", &schema, "specs").unwrap();
1725        assert_eq!(
1726            e1.entity.sections["specifies"],
1727            "## Claim\nFirst unknown.\n\n## Context\nSecond unknown.\n\n## Substance\nThird unknown.",
1728            "non-schema sections land in the catch-all in document order"
1729        );
1730        let m1 = crate::entity::generator::generate_markdown(&e1.entity, &schema);
1731        let e2 = parse_markdown(&m1, "multi-unknown.md", &schema, "specs").unwrap();
1732        let m2 = crate::entity::generator::generate_markdown(&e2.entity, &schema);
1733        assert_eq!(
1734            m1, m2,
1735            "parse→generate is idempotent over multi-unknown-section input"
1736        );
1737    }
1738
1739    // Fixture pinned by the coverage-guided long tier (local run,
1740    // 2026-08-24; corpus member `crash-fd71330e…`): parse_markdown
1741    // re-trimmed every section value after split_sections had already
1742    // normalised it, silently promoting a whitespace-prefixed first
1743    // line (vertical tab + backticks) to column 0 — where the
1744    // CommonMark referee saw a fence opener the stored form did not
1745    // have, so the section structure shifted between rounds. The
1746    // splitter's trim is the only content trim.
1747    #[test]
1748    fn first_line_whitespace_prefix_survives_storage_and_round_trips() {
1749        let schema = spec_schema();
1750        let md = "---\ntype: spec\n---\n# T\n\n## Identity\n\u{b}```\nx\n\n## Purpose\np\n";
1751        let e1 = parse_markdown(md, "vt.md", &schema, "specs").unwrap();
1752        assert_eq!(
1753            e1.entity.sections["identity"], "\u{b}```\nx",
1754            "the first visible line keeps its whitespace prefix byte-exactly"
1755        );
1756        let m1 = crate::entity::generator::generate_markdown(&e1.entity, &schema);
1757        let e2 = parse_markdown(&m1, "vt.md", &schema, "specs").unwrap();
1758        let m2 = crate::entity::generator::generate_markdown(&e2.entity, &schema);
1759        assert_eq!(m1, m2, "parse→generate is a fixpoint");
1760    }
1761
1762    // Fixture pinned by the coverage-guided long tier (0.17.0 release
1763    // readiness run, 2026-09-02; corpus member `crash-1233c134…`): a
1764    // non-schema section whose content ends inside an HTML block of a
1765    // kind no blank line ends (`<!X`, type 4) was merged in front of a
1766    // later piece. In situ a `>` line in the catch-all's own content had
1767    // closed the block, so the later piece's tilde fence opened and
1768    // masked a `## ` line into content; merged, the block stayed open,
1769    // the fence became prose, the masked line surfaced as an empty
1770    // non-schema heading, and the next round dropped it. The merge's
1771    // incremental context close now terminates HTML blocks like fences.
1772    #[test]
1773    fn merged_open_html_block_is_closed_so_later_fences_keep_masking() {
1774        let schema = spec_schema();
1775        let md = "\
1776---
1777type: spec
1778---
1779# T
1780
1781## Claim
1782<!X
1783
1784## Specifies
1785done >
1786
1787## Later
1788~~~
1789## Hidden
1790";
1791        let e1 = parse_markdown(md, "html.md", &schema, "specs").unwrap();
1792        assert_eq!(
1793            e1.entity.sections["specifies"],
1794            "done >\n\n## Claim\n<!X\n>\n\n## Later\n~~~\n## Hidden\n~~~",
1795            "the open HTML block closes before the next piece, the dangling fence after it"
1796        );
1797        let m1 = crate::entity::generator::generate_markdown(&e1.entity, &schema);
1798        let e2 = parse_markdown(&m1, "html.md", &schema, "specs").unwrap();
1799        let m2 = crate::entity::generator::generate_markdown(&e2.entity, &schema);
1800        assert_eq!(m1, m2, "parse→generate is a fixpoint");
1801    }
1802
1803    // Fixture pinned by the CI fuzz run of 2026-09-08 (corpus member
1804    // `crash-c9e7bbf7…`), the mirror image of the case above: two
1805    // adjacent non-schema sections, the first ending inside a `<!X`
1806    // block that the SECOND closes with its `>` line, so the second
1807    // heading stood inside the block. In situ the `<!--` before that
1808    // line was inert inside the block and the tilde fence after it
1809    // masked `## Hidden` into content. Written from a neutral start,
1810    // the `<!--` is a live comment, the fence is dead and `## Hidden`
1811    // is a heading; the second parse split there and carried a second
1812    // `-->`. The splitter now reads a section that stood inside a
1813    // block the way it will be written, so `## Hidden` is a boundary
1814    // on the first parse already (an empty non-schema section, dropped
1815    // as every such section is) and the comment closes before it.
1816    #[test]
1817    fn section_that_stood_inside_the_previous_sections_block_is_read_as_written() {
1818        let schema = spec_schema();
1819        let md = "\
1820---
1821type: spec
1822---
1823# T
1824
1825## First
1826<!X
1827
1828## Second
1829<!--
1830>
1831~~~
1832## Hidden
1833";
1834        let e1 = parse_markdown(md, "html.md", &schema, "specs").unwrap();
1835        assert_eq!(
1836            e1.entity.sections["specifies"], "## First\n<!X\n>\n\n## Second\n<!--\n>\n~~~\n-->",
1837            "the second section ends where a neutral read would split it, and its comment closes there"
1838        );
1839        assert_eq!(
1840            e1.entity.raw_section_headings,
1841            vec!["First", "Second", "Hidden"],
1842            "the surfaced line is a boundary on the first parse"
1843        );
1844        let m1 = crate::entity::generator::generate_markdown(&e1.entity, &schema);
1845        let e2 = parse_markdown(&m1, "html.md", &schema, "specs").unwrap();
1846        let m2 = crate::entity::generator::generate_markdown(&e2.entity, &schema);
1847        assert_eq!(m1, m2, "parse→generate is a fixpoint");
1848    }
1849
1850    // Fixture pinned by the CI fuzz run of 2026-09-09 (corpus member
1851    // `crash-ce631bf5…`), the sibling with no section before the block:
1852    // the `<!X` block opens in the preamble under the title, so the only
1853    // section's heading stands inside it and no closer between merged
1854    // pieces exists to blame. Same in-situ reading (inert `<!--`, live
1855    // fence, masked `## Hidden`), same neutral reading (live comment,
1856    // dead fence, surfaced heading); the splitter's second pass makes
1857    // the first parse agree with the second.
1858    #[test]
1859    fn section_that_stood_inside_a_preamble_block_is_read_as_written() {
1860        let schema = spec_schema();
1861        let md = "\
1862---
1863type: spec
1864---
1865# T
1866<!X
1867## Only
1868<!--
1869>
1870~~~
1871## Hidden
1872";
1873        let e1 = parse_markdown(md, "html.md", &schema, "specs").unwrap();
1874        assert_eq!(
1875            e1.entity.sections["specifies"], "## Only\n<!--\n>\n~~~\n-->",
1876            "the section ends where a neutral read would split it, and its comment closes there"
1877        );
1878        let m1 = crate::entity::generator::generate_markdown(&e1.entity, &schema);
1879        let e2 = parse_markdown(&m1, "html.md", &schema, "specs").unwrap();
1880        let m2 = crate::entity::generator::generate_markdown(&e2.entity, &schema);
1881        assert_eq!(m1, m2, "parse→generate is a fixpoint");
1882    }
1883
1884    // Fixture pinned by the coverage-guided long tier (first dispatch,
1885    // 2026-08-24; corpus member `crash-de0c69e0…`): the splitter's full
1886    // content trim promoted an INDENTED heading-lookalike on the first
1887    // content line (` ## Specifies`) to column 0 inside stored content;
1888    // the catch-all re-emit then made the next parse read it as a real
1889    // duplicate section heading, whose first-wins rule dropped the
1890    // content — structure from content, and a broken fixpoint. Leading
1891    // blank lines still drop; the first visible line keeps its
1892    // indentation.
1893    #[test]
1894    fn indented_heading_lookalike_stays_content_and_round_trips() {
1895        let md = "\
1896---
1897type: spec
1898---
1899# Promoted Heading
1900
1901## Identity
1902
1903Base.
1904
1905## Unknown Extra
1906
1907 ## Specifies
1908
1909Some content that must survive.
1910";
1911        let schema = spec_schema();
1912        let e1 = parse_markdown(md, "indent.md", &schema, "specs").unwrap();
1913        assert!(
1914            e1.entity.sections["specifies"].contains(" ## Specifies"),
1915            "the indented lookalike keeps its indentation inside the catch-all"
1916        );
1917        assert!(
1918            e1.entity.sections["specifies"].contains("Some content that must survive."),
1919            "content after the lookalike is preserved"
1920        );
1921        let m1 = crate::entity::generator::generate_markdown(&e1.entity, &schema);
1922        let e2 = parse_markdown(&m1, "indent.md", &schema, "specs").unwrap();
1923        let m2 = crate::entity::generator::generate_markdown(&e2.entity, &schema);
1924        assert_eq!(
1925            m1, m2,
1926            "parse→generate is a fixpoint after one normalising round"
1927        );
1928        assert!(
1929            e2.entity.sections["specifies"].contains("Some content that must survive."),
1930            "no content is lost across rounds"
1931        );
1932    }
1933
1934    #[test]
1935    fn compute_hash_deterministic() {
1936        let hash1 = compute_hash("test content");
1937        let hash2 = compute_hash("test content");
1938        assert_eq!(hash1, hash2);
1939        assert_eq!(hash1.len(), 16);
1940    }
1941
1942    #[test]
1943    fn compute_hash_differs() {
1944        let hash1 = compute_hash("content a");
1945        let hash2 = compute_hash("content b");
1946        assert_ne!(hash1, hash2);
1947    }
1948
1949    #[test]
1950    fn is_float_literal_matches() {
1951        assert!(is_float_literal("0.85"));
1952        assert!(is_float_literal("-1.5"));
1953        assert!(is_float_literal("100.0"));
1954        assert!(!is_float_literal(".5"));
1955        assert!(!is_float_literal("1."));
1956        assert!(!is_float_literal("42"));
1957        assert!(!is_float_literal("hello"));
1958    }
1959
1960    #[test]
1961    fn is_integer_literal_matches() {
1962        assert!(is_integer_literal("42"));
1963        assert!(is_integer_literal("-1"));
1964        assert!(is_integer_literal("0"));
1965        assert!(!is_integer_literal("0.5"));
1966        assert!(!is_integer_literal("hello"));
1967        assert!(!is_integer_literal(""));
1968    }
1969
1970    // Regression lock for metadata-key order. The parser reads frontmatter
1971    // line-by-line into an IndexMap, so metadata iteration yields the file's
1972    // declared key order. Render sites iterate entity.metadata directly (see
1973    // `render::render_entity_markdown`), so any regression to HashMap
1974    // reintroduces hash-seed-dependent frontmatter ordering in MCP output.
1975    #[test]
1976    fn parse_preserves_frontmatter_key_order() {
1977        let md = "\
1978---
1979type: principle
1980universality: domain-wide
1981authority: proposed
1982tags: a, b, c
1983created_date: 2026-01-15
1984last_modified: 2026-04-12
1985---
1986# Key Order
1987";
1988        let result = parse_markdown(
1989            md,
1990            "key-order.md",
1991            &type_by_name(builtin_names::PRINCIPLE).unwrap(),
1992            "knowledge",
1993        )
1994        .unwrap();
1995        let keys: Vec<&str> = result.entity.metadata.keys().map(|s| s.as_str()).collect();
1996        assert_eq!(
1997            keys,
1998            vec![
1999                "type",
2000                "universality",
2001                "authority",
2002                "tags",
2003                "created_date",
2004                "last_modified",
2005            ],
2006            "metadata iteration must preserve frontmatter declaration order"
2007        );
2008    }
2009
2010    // Regression lock for section-order round-trip stability. Today this
2011    // passes by construction: the parser inserts keys in schema-declared
2012    // order, the generator writes them in schema-declared order, and
2013    // `IndexMap` preserves that order across re-parses. HashMap iteration
2014    // order was the hole — an IndexMap-based entity.sections closes it.
2015    // Keep the test; if a future refactor reintroduces a HashMap anywhere on
2016    // the parse/write path, this catches it.
2017    #[test]
2018    fn parse_write_roundtrip_preserves_section_order() {
2019        let md = "\
2020---
2021type: spec
2022created_date: 2026-01-15
2023last_modified: 2026-04-12
2024level: M0
2025---
2026# Order Roundtrip
2027
2028## Identity
2029
2030Identity content.
2031
2032## Purpose
2033
2034Purpose content.
2035
2036## Specifies
2037
2038Specifies content.
2039";
2040        let schema = spec_schema();
2041        let first = parse_markdown(md, "order-roundtrip.md", &schema, "specs").unwrap();
2042        let regenerated = crate::entity::generator::generate_markdown(&first.entity, &schema);
2043        let second = parse_markdown(&regenerated, "order-roundtrip.md", &schema, "specs").unwrap();
2044
2045        let first_keys: Vec<&String> = first.entity.sections.keys().collect();
2046        let second_keys: Vec<&String> = second.entity.sections.keys().collect();
2047        assert_eq!(
2048            first_keys, second_keys,
2049            "section iteration order must survive parse -> generate -> parse"
2050        );
2051    }
2052
2053    // ------------------------------------------------------------------
2054    // Heading-spans extraction (H3–H6)
2055    //
2056    // These lock the parser contract: one extra pass per section that
2057    // records H3+ headings as a side-struct. Flat storage; level skips
2058    // are tolerated; code blocks are ignored. See
2059    // `extract_heading_spans`.
2060    // ------------------------------------------------------------------
2061
2062    #[test]
2063    fn parser_extracts_single_h3() {
2064        let md = "\
2065---
2066type: spec
2067---
2068# Entity
2069
2070## Identity
2071
2072Body.
2073
2074## Specifies
2075
2076### Response Shapes
2077
2078Content under response shapes.
2079";
2080        let result = parse_markdown(md, "h3-single.md", &spec_schema(), "specs").unwrap();
2081        let spans = result
2082            .entity
2083            .heading_spans
2084            .get("specifies")
2085            .expect("specifies section should have spans");
2086        assert_eq!(spans.len(), 1);
2087        assert_eq!(spans[0].level, 3);
2088        assert_eq!(spans[0].title, "Response Shapes");
2089        // The section is trimmed, so the H3 sits at offset 0.
2090        assert_eq!(spans[0].start_offset, 0);
2091        let section = result.entity.sections.get("specifies").unwrap();
2092        assert_eq!(spans[0].end_offset, section.len());
2093        // Non-specifies sections either get no entry or the content has no H3+ headings.
2094        assert!(
2095            result
2096                .entity
2097                .heading_spans
2098                .get("identity")
2099                .is_none_or(Vec::is_empty)
2100        );
2101    }
2102
2103    #[test]
2104    fn parser_extracts_nested_h3_h4() {
2105        let md = "\
2106---
2107type: spec
2108---
2109# Entity
2110
2111## Identity
2112
2113Body.
2114
2115## Specifies
2116
2117### Outer
2118
2119Outer body.
2120
2121#### Inner
2122
2123Inner body.
2124";
2125        let result = parse_markdown(md, "h3-h4.md", &spec_schema(), "specs").unwrap();
2126        let spans = result.entity.heading_spans.get("specifies").unwrap();
2127        assert_eq!(spans.len(), 2, "both H3 and H4 must be recorded");
2128        assert_eq!(spans[0].level, 3);
2129        assert_eq!(spans[0].title, "Outer");
2130        assert_eq!(spans[1].level, 4);
2131        assert_eq!(spans[1].title, "Inner");
2132        assert!(
2133            spans[0].start_offset < spans[1].start_offset,
2134            "spans must be in document order"
2135        );
2136        // H3 contains H4: H3.end_offset must cover H4.start_offset.
2137        assert!(
2138            spans[0].end_offset > spans[1].start_offset,
2139            "outer H3 must contain inner H4 by offset"
2140        );
2141    }
2142
2143    #[test]
2144    fn parser_ignores_headings_in_code_blocks() {
2145        let md = "\
2146---
2147type: spec
2148---
2149# Entity
2150
2151## Identity
2152
2153Body.
2154
2155## Specifies
2156
2157Prefix.
2158
2159```
2160### Not a heading
2161Still code.
2162```
2163
2164Suffix.
2165";
2166        let result = parse_markdown(md, "h3-code.md", &spec_schema(), "specs").unwrap();
2167        let spans = result
2168            .entity
2169            .heading_spans
2170            .get("specifies")
2171            .cloned()
2172            .unwrap_or_default();
2173        assert!(
2174            spans.is_empty(),
2175            "a '### ' inside a fenced block must not register as a heading span: {spans:?}"
2176        );
2177    }
2178
2179    #[test]
2180    fn parser_handles_level_skip() {
2181        let md = "\
2182---
2183type: spec
2184---
2185# Entity
2186
2187## Identity
2188
2189Body.
2190
2191## Specifies
2192
2193#### Skipped To H4
2194
2195Content under a sudden H4 — no virtual H3 is inserted.
2196";
2197        let result = parse_markdown(md, "h2-h4.md", &spec_schema(), "specs").unwrap();
2198        let spans = result.entity.heading_spans.get("specifies").unwrap();
2199        assert_eq!(spans.len(), 1);
2200        assert_eq!(spans[0].level, 4);
2201        assert_eq!(spans[0].title, "Skipped To H4");
2202    }
2203
2204    #[test]
2205    fn parser_handles_duplicate_siblings() {
2206        let md = "\
2207---
2208type: spec
2209---
2210# Entity
2211
2212## Identity
2213
2214Body.
2215
2216## Specifies
2217
2218### Same Title
2219
2220First occurrence body.
2221
2222### Same Title
2223
2224Second occurrence body.
2225";
2226        let result = parse_markdown(md, "h3-dup.md", &spec_schema(), "specs").unwrap();
2227        let spans = result.entity.heading_spans.get("specifies").unwrap();
2228        assert_eq!(spans.len(), 2, "duplicate siblings must produce two spans");
2229        assert_eq!(spans[0].title, spans[1].title);
2230        assert_ne!(
2231            spans[0].start_offset, spans[1].start_offset,
2232            "spans with identical titles must be distinguishable by offset"
2233        );
2234        // Siblings at the same level: neither contains the other.
2235        assert!(
2236            spans[0].end_offset <= spans[1].start_offset,
2237            "first sibling must close before the second starts"
2238        );
2239    }
2240
2241    // Duplicate `## Heading` lines for a schema-declared key collapse to the
2242    // first occurrence's body and emit a `DuplicateSectionHeading` warning.
2243    // Catch-all keys absorb arbitrary headings by design and do not warn.
2244
2245    #[test]
2246    fn duplicate_declared_heading_two_populated_keeps_first_warns() {
2247        let md = "---\ntype: spec\n---\n# Title\n\n## Identity\n\nfirst body\n\n## Identity\n\nsecond body\n";
2248        let result = parse_markdown(md, "x.md", &spec_schema(), "v").unwrap();
2249        assert_eq!(
2250            result.entity.sections.get("identity").map(String::as_str),
2251            Some("first body"),
2252            "first body must win"
2253        );
2254        assert!(
2255            !result
2256                .entity
2257                .sections
2258                .get("identity")
2259                .unwrap()
2260                .contains("## Identity"),
2261            "storage value must not embed a duplicate heading"
2262        );
2263        assert_eq!(result.parse_warnings.len(), 1);
2264        match &result.parse_warnings[0] {
2265            crate::ops::WarningHint::DuplicateSectionHeading {
2266                section_key,
2267                heading,
2268                occurrences,
2269                ..
2270            } => {
2271                assert_eq!(section_key, "identity");
2272                assert_eq!(heading, "Identity");
2273                assert_eq!(*occurrences, 2);
2274            }
2275            other => panic!("expected DuplicateSectionHeading, got {other:?}"),
2276        }
2277    }
2278
2279    #[test]
2280    fn duplicate_declared_heading_blank_then_populated_keeps_blank() {
2281        // First-wins is mechanical: a blank first occurrence wins over a
2282        // populated second one. The warning surfaces so the operator
2283        // notices content was discarded.
2284        let md =
2285            "---\ntype: spec\n---\n# Title\n\n## Identity\n\n## Identity\n\nleftover content\n";
2286        let result = parse_markdown(md, "x.md", &spec_schema(), "v").unwrap();
2287        assert_eq!(
2288            result.entity.sections.get("identity").map(String::as_str),
2289            Some(""),
2290            "first (blank) occurrence wins; second body is dropped"
2291        );
2292        assert_eq!(result.parse_warnings.len(), 1);
2293    }
2294
2295    #[test]
2296    fn duplicate_declared_heading_three_occurrences() {
2297        let md = "---\ntype: spec\n---\n# Title\n\n## Constraints\n\nA\n\n## Constraints\n\n## Constraints\n\nC\n";
2298        let result = parse_markdown(md, "x.md", &spec_schema(), "v").unwrap();
2299        assert_eq!(
2300            result
2301                .entity
2302                .sections
2303                .get("constraints")
2304                .map(String::as_str),
2305            Some("A"),
2306        );
2307        assert_eq!(result.parse_warnings.len(), 1);
2308        match &result.parse_warnings[0] {
2309            crate::ops::WarningHint::DuplicateSectionHeading { occurrences, .. } => {
2310                assert_eq!(*occurrences, 3);
2311            }
2312            _ => unreachable!(),
2313        }
2314    }
2315
2316    #[test]
2317    fn no_warning_when_each_declared_section_appears_once() {
2318        let md = "---\ntype: spec\n---\n# Title\n\n## Identity\n\nID\n\n## Purpose\n\nP\n\n## Constraints\n\nC\n";
2319        let result = parse_markdown(md, "x.md", &spec_schema(), "v").unwrap();
2320        assert!(result.parse_warnings.is_empty());
2321    }
2322
2323    #[test]
2324    fn no_warning_when_catch_all_section_repeats() {
2325        // `specifies` is the spec schema's catch-all section. Repetition
2326        // there is silent — duplicates only warn for non-catch-all keys.
2327        let md =
2328            "---\ntype: spec\n---\n# Title\n\n## Specifies\n\nfirst\n\n## Specifies\n\nsecond\n";
2329        let result = parse_markdown(md, "x.md", &spec_schema(), "v").unwrap();
2330        assert!(
2331            result.parse_warnings.is_empty(),
2332            "catch-all repetition must not warn"
2333        );
2334    }
2335
2336    // Three `## Realization` headings on a spec entity. The default-schema
2337    // `spec` does not declare `realization`, so it flows to the catch-all
2338    // `specifies` bucket and emits no warning, but the storage must still
2339    // not concatenate duplicate heading bytes — that was the bug being
2340    // fixed. Workspaces that declare `realization` (e.g. `software@0.1.0`)
2341    // additionally surface a `DuplicateSectionHeading` warning.
2342    #[test]
2343    fn duplicate_realization_does_not_concatenate_headers_in_storage() {
2344        let md = "---\ntype: spec\n---\n# Title\n\n## Identity\n\nID\n\n## Realization\n\n- a.mjs\n- b.mjs\n\n## Realization\n\n## Realization\n\n- c.mjs\n\n## Constraints\n\nC\n";
2345        let result = parse_markdown(md, "x.md", &spec_schema(), "v").unwrap();
2346        let catch_all = result.entity.sections.get("specifies").unwrap();
2347        let header_count = catch_all.matches("## Realization").count();
2348        assert!(
2349            header_count <= 1,
2350            "catch-all bucket must not contain multiple `## Realization` headers — got {header_count}: {catch_all:?}"
2351        );
2352    }
2353
2354    // After a parse → render round-trip, an entity that was loaded from a
2355    // markdown file with three `## Identity` headings emits exactly one
2356    // `## Identity` heading on re-render. This is the self-heal contract:
2357    // the next read-modify-write of a duplicate-heading entity collapses
2358    // the markdown to one heading per declared section.
2359    #[test]
2360    fn parse_render_round_trip_collapses_duplicate_headings() {
2361        let md = "---\ntype: spec\n---\n# Title\n\n## Identity\n\nA\n\n## Identity\n\n## Identity\n\nC\n\n## Purpose\n\nP\n";
2362        let result = parse_markdown(md, "x.md", &spec_schema(), "v").unwrap();
2363        let rendered = crate::render::render_entity_markdown(&result.entity, None);
2364        let identity_count = rendered.matches("## Identity").count();
2365        assert_eq!(
2366            identity_count, 1,
2367            "rendered output must carry exactly one `## Identity`, got {identity_count}: {rendered}"
2368        );
2369        // First-wins: the rendered Identity body is `A`, not `C`.
2370        assert!(rendered.contains("\n## Identity\n\nA\n"));
2371        assert!(!rendered.contains("C\n"), "second body must not survive");
2372    }
2373}
2374
2375/// End-to-end pins for the six verified code-block misparse classes,
2376/// on the real entity paths: section splitting, title extraction,
2377/// heading spans, and wiki-link extraction. The unit-level pins for
2378/// the mask itself live in [`crate::markdown`]; these assert the
2379/// classes are actually fixed where they did damage.
2380#[cfg(test)]
2381mod commonmark_referee {
2382    use super::*;
2383    use memstead_schema::{builtin_names, type_by_name};
2384    use std::sync::Arc;
2385
2386    fn spec_schema() -> Arc<TypeDefinition> {
2387        type_by_name(builtin_names::SPEC).unwrap()
2388    }
2389
2390    /// Wrap a `## Specifies` body in a minimal, valid spec entity.
2391    fn entity_with_specifies(body: &str) -> ParseResult {
2392        let md = format!(
2393            "---\ntype: spec\n---\n\n# Referee Test\n\n## Identity\n\nx\n\n## Specifies\n\n{body}\n"
2394        );
2395        parse_markdown(&md, "referee-test.md", &spec_schema(), "specs").unwrap()
2396    }
2397
2398    fn headings(result: &ParseResult) -> Vec<&str> {
2399        result
2400            .entity
2401            .raw_section_headings
2402            .iter()
2403            .map(String::as_str)
2404            .collect()
2405    }
2406
2407    fn link_targets(result: &ParseResult) -> Vec<String> {
2408        result.inline_links.iter().map(|id| id.0.clone()).collect()
2409    }
2410
2411    /// The complement first: without it, every assertion below could
2412    /// pass because the paths do nothing at all.
2413    #[test]
2414    fn complement_prose_headings_and_links_still_work() {
2415        let r = entity_with_specifies("See [[real-target]] here.");
2416        assert_eq!(headings(&r), vec!["Identity", "Specifies"]);
2417        assert_eq!(link_targets(&r), vec!["specs--real-target".to_string()]);
2418        assert_eq!(r.entity.title, "Referee Test");
2419    }
2420
2421    #[test]
2422    fn class_1_indented_code_block() {
2423        let r = entity_with_specifies("Example:\n\n    ## Not A Section\n    [[not-a-link]]\n");
2424        assert_eq!(headings(&r), vec!["Identity", "Specifies"]);
2425        assert!(link_targets(&r).is_empty(), "{:?}", link_targets(&r));
2426    }
2427
2428    #[test]
2429    fn class_2_fence_indented_one_to_three_spaces() {
2430        let r = entity_with_specifies(
2431            "- item\n\n   ```\n   ## Not A Section\n   [[not-a-link]]\n   ```\n",
2432        );
2433        assert_eq!(headings(&r), vec!["Identity", "Specifies"]);
2434        assert!(link_targets(&r).is_empty(), "{:?}", link_targets(&r));
2435    }
2436
2437    #[test]
2438    fn class_3_tilde_fence() {
2439        let r = entity_with_specifies("~~~\n## Not A Section\n[[not-a-link]]\n~~~\n");
2440        assert_eq!(headings(&r), vec!["Identity", "Specifies"]);
2441        assert!(link_targets(&r).is_empty(), "{:?}", link_targets(&r));
2442    }
2443
2444    #[test]
2445    fn class_4_info_string_on_the_closing_line() {
2446        let r = entity_with_specifies(
2447            "```\ncode\n``` still-code\n## Not A Section\n[[not-a-link]]\n```\n",
2448        );
2449        assert_eq!(headings(&r), vec!["Identity", "Specifies"]);
2450        assert!(link_targets(&r).is_empty(), "{:?}", link_targets(&r));
2451    }
2452
2453    #[test]
2454    fn class_5_fence_inside_a_blockquote() {
2455        let r = entity_with_specifies("> ```\n> ## Not A Section\n> [[not-a-link]]\n> ```\n");
2456        assert_eq!(headings(&r), vec!["Identity", "Specifies"]);
2457        assert!(link_targets(&r).is_empty(), "{:?}", link_targets(&r));
2458    }
2459
2460    #[test]
2461    fn class_6_opening_fence_length_is_honoured_on_close() {
2462        let r = entity_with_specifies("````\n```\n## Not A Section\n[[not-a-link]]\n```\n````\n");
2463        assert_eq!(headings(&r), vec!["Identity", "Specifies"]);
2464        assert!(link_targets(&r).is_empty(), "{:?}", link_targets(&r));
2465    }
2466
2467    /// The title extractor was the one scanner with no masking at all.
2468    #[test]
2469    fn a_heading_inside_a_code_block_never_becomes_the_title() {
2470        let md =
2471            "---\ntype: spec\n---\n\n```\n# Fake Title\n```\n\n# Real Title\n\n## Identity\n\nx\n";
2472        let r = parse_markdown(md, "title-test.md", &spec_schema(), "specs").unwrap();
2473        assert_eq!(r.entity.title, "Real Title");
2474    }
2475
2476    /// …and when the code block is the whole body, the filename
2477    /// fallback applies rather than a title mined out of code.
2478    #[test]
2479    fn a_code_block_only_body_falls_back_to_the_filename() {
2480        let md = "---\ntype: spec\n---\n\n    # Fake Title\n\n## Identity\n\nx\n";
2481        let r = parse_markdown(md, "fallback-test.md", &spec_schema(), "specs").unwrap();
2482        assert_eq!(r.entity.title, "fallback-test");
2483    }
2484
2485    #[test]
2486    fn heading_spans_ignore_code_block_content() {
2487        let r = entity_with_specifies("### Real Sub\n\n~~~\n### Fake Sub\n~~~\n");
2488        let spans = r.entity.heading_spans.get("specifies").expect("spans");
2489        let titles: Vec<&str> = spans.iter().map(|s| s.title.as_str()).collect();
2490        assert_eq!(titles, vec!["Real Sub"]);
2491    }
2492
2493    /// One definition of "not visible to a link scanner": a link the
2494    /// strict validator cannot see is a link no path turns into an
2495    /// edge. Multi-backtick spans are the case a delimiter-count regex
2496    /// slices through.
2497    #[test]
2498    fn inline_code_spans_hide_links_on_the_extraction_path() {
2499        let r = entity_with_specifies("`[[hidden-one]]` and ``[[hidden-two]]`` but [[visible]].");
2500        assert_eq!(link_targets(&r), vec!["specs--visible".to_string()]);
2501    }
2502
2503    /// The empty-target asymmetry: the strict extractor now *sees*
2504    /// `[[]]` and routes it to the same refusal the validator emits,
2505    /// instead of a pattern that could not match it at all.
2506    #[test]
2507    fn empty_wiki_link_target_is_refused_by_the_strict_extractor() {
2508        let errors = extract_inline_links("an empty [[]] link", "specs")
2509            .expect_err("empty target must refuse");
2510        assert_eq!(errors.len(), 1, "{errors:?}");
2511    }
2512
2513    /// The read side tolerates drift by ignoring what it cannot
2514    /// decode — but it sees the same token the strict side refuses.
2515    #[test]
2516    fn empty_wiki_link_target_yields_no_id_on_the_lenient_path() {
2517        assert!(extract_inline_links_lenient("an empty [[]] link", "specs").is_empty());
2518    }
2519
2520    /// A conflicted file must be refused however its frontmatter is
2521    /// shaped. Masking the whole file let a YAML value that reads as a
2522    /// fence opener blank the body — markers included — so the file
2523    /// loaded as a normal entity with BOTH merge sides fused into one
2524    /// body, which is the exact outcome the guard exists to prevent.
2525    #[test]
2526    fn merge_conflict_markers_are_seen_through_fence_shaped_frontmatter() {
2527        let body = "\n# T\n\n## Identity\n\n<<<<<<< HEAD\nours\n=======\ntheirs\n>>>>>>> branch\n";
2528        for fm in [
2529            "---\ntype: spec\n---",
2530            "---\ntype: spec\nnotes: |\n  ```rust\n  fn x() {}\n---",
2531            "---\ntype: spec\nnotes: |\n   ~~~\n---",
2532            "---\ntype: spec\nnotes: |\n    indented block\n---",
2533        ] {
2534            assert!(
2535                has_merge_conflict_markers(&format!("{fm}{body}")),
2536                "conflict markers must be seen through frontmatter: {fm:?}"
2537            );
2538        }
2539    }
2540
2541    /// …and markers in the frontmatter itself count: git writes them
2542    /// wherever the hunks fall, including above the `---`.
2543    #[test]
2544    fn merge_conflict_markers_in_frontmatter_are_seen() {
2545        let content =
2546            "---\n<<<<<<< HEAD\ntype: spec\n=======\ntype: memo\n>>>>>>> branch\n---\n\n# T\n";
2547        assert!(has_merge_conflict_markers(content));
2548    }
2549
2550    /// Complement: a fenced code example documenting conflict markers
2551    /// in a section body still does not trip the guard.
2552    #[test]
2553    fn a_fenced_conflict_marker_example_still_does_not_trip_the_guard() {
2554        let content = "---\ntype: spec\n---\n\n# T\n\n## Identity\n\n```\n<<<<<<< HEAD\nours\n=======\ntheirs\n>>>>>>> branch\n```\n";
2555        assert!(!has_merge_conflict_markers(content));
2556    }
2557
2558    /// A relationship row inside a code block is an example of the
2559    /// syntax, not a relationship. It used to become a live edge and an
2560    /// auto-stub while the strict validator — which masks — could not
2561    /// see the link at all: one path synthesising an edge from what
2562    /// another path refuses to see.
2563    #[test]
2564    fn a_relationship_row_inside_a_code_block_is_not_a_relationship() {
2565        for body in [
2566            "```\n- **REFERENCES**: [[ghost]]\n```",
2567            "~~~\n- **REFERENCES**: [[ghost]]\n~~~",
2568            "    - **REFERENCES**: [[ghost]]",
2569            "> ```\n> - **REFERENCES**: [[ghost]]\n> ```",
2570            "````\n```\n- **REFERENCES**: [[ghost]]\n```\n````",
2571        ] {
2572            let (rels, _) = parse_relationships_with_warnings(body, "specs", None);
2573            assert!(
2574                rels.is_empty(),
2575                "code-block row must not become an edge: {body:?} -> {rels:?}"
2576            );
2577        }
2578    }
2579
2580    /// …and a row hidden inside an INLINE CODE SPAN is not one either.
2581    /// A blocks-only mask left this row invisible to the strict
2582    /// validator and to every link extractor — both of which mask
2583    /// spans — while still building an edge and a stub from it. A
2584    /// multi-line span is the shape that bites: a lazy paragraph
2585    /// continuation keeps the backticks open across the row.
2586    #[test]
2587    fn a_relationship_row_inside_an_inline_code_span_is_not_a_relationship() {
2588        for body in [
2589            // The row is indented, so it does not interrupt the
2590            // paragraph as a list — it is a lazy continuation and the
2591            // backtick pair holds the span open across all three lines.
2592            // (At column 0 a `-` DOES start a list, the span never
2593            // forms, and the row is a real relationship — correctly.)
2594            "Example `open\n    - **REFERENCES**: [[ghost]]\nclose`",
2595            "A `- **REFERENCES**: [[ghost]]` sample.",
2596            "A ``- **REFERENCES**: [[ghost]]`` sample.",
2597        ] {
2598            let (rels, _) = parse_relationships_with_warnings(body, "specs", None);
2599            assert!(
2600                rels.is_empty(),
2601                "code-span row must not become an edge: {body:?} -> {rels:?}"
2602            );
2603        }
2604    }
2605
2606    /// Complement: a real row still parses, keeps its type, target and
2607    /// em-dash description, and still warns on an ambiguous delimiter —
2608    /// every captured span is read from the original, not the mask.
2609    #[test]
2610    fn real_relationship_rows_are_unchanged_by_the_mask() {
2611        let body = "- **REFERENCES**: [[alpha]]\n- **uses**: [[beta]] — because it must\n\n```\n- **REFERENCES**: [[ghost]]\n```\n";
2612        let (rels, _) = parse_relationships_with_warnings(body, "specs", None);
2613        assert_eq!(rels.len(), 2, "{rels:?}");
2614        assert_eq!(rels[0].rel_type, "REFERENCES");
2615        assert_eq!(rels[0].target.0, "specs--alpha");
2616        assert_eq!(rels[0].description, None);
2617        assert_eq!(
2618            rels[1].rel_type, "USES",
2619            "case is normalised from the original"
2620        );
2621        assert_eq!(rels[1].target.0, "specs--beta");
2622        assert_eq!(rels[1].description.as_deref(), Some("because it must"));
2623    }
2624
2625    #[test]
2626    fn ambiguous_delimiter_warning_still_fires_on_a_real_row() {
2627        let id = file_path_to_id("x.md", "specs");
2628        let (_, warnings) = parse_relationships_with_warnings(
2629            "- **REFERENCES**: [[alpha]] -- not an em dash\n",
2630            "specs",
2631            Some(&id),
2632        );
2633        assert_eq!(warnings.len(), 1, "{warnings:?}");
2634    }
2635
2636    /// Frontmatter is not markdown. Masking the whole file would hand
2637    /// a CommonMark parser YAML it can read as block structure: a
2638    /// value line that looks like a fence opener (legal at 1–3 spaces
2639    /// since the indented-fence class was fixed) would open a code
2640    /// block that runs past the closing `---` and mask the entire
2641    /// body — no title, no sections, no links. The split happens
2642    /// first; only the body is masked.
2643    #[test]
2644    fn frontmatter_never_opens_a_code_block_over_the_body() {
2645        for fm in [
2646            "notes: |\n  ```rust",
2647            "notes: |\n   ~~~",
2648            "notes: |\n  ```\n  still open",
2649            "notes: |\n    indented block\n",
2650        ] {
2651            let md = format!(
2652                "---\ntype: spec\n{fm}\n---\n\n# Real Title\n\n## Identity\n\nSee [[a-link]].\n"
2653            );
2654            let r = parse_markdown(&md, "fm-test.md", &spec_schema(), "specs").unwrap();
2655            assert_eq!(
2656                r.entity.title, "Real Title",
2657                "frontmatter ate the title: {fm:?}"
2658            );
2659            assert_eq!(
2660                headings(&r),
2661                vec!["Identity"],
2662                "frontmatter ate the sections: {fm:?}"
2663            );
2664            assert_eq!(
2665                link_targets(&r),
2666                vec!["specs--a-link".to_string()],
2667                "frontmatter ate the links: {fm:?}"
2668            );
2669        }
2670    }
2671}