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(§ions_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`. A quoted value
452/// keeps every ` #` inside its quotes (`"Project #1" # note` → `"Project
453/// #1"`): the comment can only begin after the closing quote. Inside a
454/// double-quoted value `\"` is an escaped quote and does not close it.
455fn strip_inline_comment(s: &str) -> &str {
456 let close = match s.as_bytes().first() {
457 Some(b'"') => closing_quote(s, '"', true),
458 Some(b'\'') => closing_quote(s, '\'', false),
459 _ => None,
460 };
461 let (quoted, rest) = match close {
462 Some(end) => (&s[..=end], &s[end + 1..]),
463 None => ("", s),
464 };
465 match rest.find(" #") {
466 Some(idx) if quoted.is_empty() => s[..idx].trim_end(),
467 Some(idx) => &s[..quoted.len() + idx],
468 None => s,
469 }
470 .trim_end()
471}
472
473/// The byte index of the quote that closes a value opening with `quote`
474/// at byte 0, honouring backslash escapes when `escapes` is set; `None`
475/// when the value never closes (it is then read unquoted, as before).
476fn closing_quote(s: &str, quote: char, escapes: bool) -> Option<usize> {
477 let mut escaped = false;
478 for (i, c) in s.char_indices().skip(1) {
479 if escaped {
480 escaped = false;
481 continue;
482 }
483 if escapes && c == '\\' {
484 escaped = true;
485 continue;
486 }
487 if c == quote {
488 return Some(i);
489 }
490 }
491 None
492}
493
494/// Strip surrounding quotes: `"value"` or `'value'` → `value`. Inside a
495/// double-quoted value `\"` reads as `"` and `\\` as `\`, the two
496/// escapes the writer emits; every other backslash is kept as is.
497/// A lone quote character is not a quoted value — `len >= 2` keeps the
498/// slice in bounds (a 1-char `"` satisfies both starts_with and ends_with).
499fn strip_quotes(s: &str) -> String {
500 if s.len() >= 2 && s.starts_with('"') && s.ends_with('"') {
501 let inner = &s[1..s.len() - 1];
502 let mut out = String::with_capacity(inner.len());
503 let mut chars = inner.chars().peekable();
504 while let Some(c) = chars.next() {
505 if c == '\\' && matches!(chars.peek(), Some('"') | Some('\\')) {
506 out.push(chars.next().unwrap());
507 } else {
508 out.push(c);
509 }
510 }
511 out
512 } else if s.len() >= 2 && s.starts_with('\'') && s.ends_with('\'') {
513 s[1..s.len() - 1].to_string()
514 } else {
515 s.to_string()
516 }
517}
518
519// ---------------------------------------------------------------------------
520// Code block masking
521// ---------------------------------------------------------------------------
522
523/// Mask every CommonMark code block by replacing its bytes with spaces
524/// (preserves line count and byte offsets). Handles unclosed blocks
525/// safely — they mask to end of text.
526///
527/// The definition lives in [`crate::markdown`] — one referee for every
528/// content reader in the engine. Re-exported here because this module's
529/// callers are the historical ones.
530pub use crate::markdown::{mask_code_blocks, mask_code_blocks_and_spans};
531
532// ---------------------------------------------------------------------------
533// Merge-conflict detection
534// ---------------------------------------------------------------------------
535
536/// True when `text` — a whole entity file — carries a complete git
537/// merge-conflict block: an ordered `<<<<<<< …` / `=======` /
538/// `>>>>>>> …` triple at line starts.
539///
540/// The frontmatter is scanned **raw** and the body over
541/// [`mask_code_blocks`] output. Both halves of that split are
542/// load-bearing:
543///
544/// - Masking the body is why a code example documenting conflict
545/// markers never trips the check. It is a legibility trade-off, not
546/// a soundness one: a real conflict whose markers all fall inside
547/// one code block goes undetected (the file then loads/degrades
548/// exactly as it did before this check existed) — git writes markers
549/// without regard for fences, so that shape is rare, while marker
550/// examples in documentation entities are not.
551/// - Frontmatter is **not** masked, because frontmatter is not
552/// markdown. Handing it to a CommonMark parser invents block
553/// structure that is not there: a YAML value that reads as a fence
554/// opener (legal at 1–3 spaces) opens a code block that runs past
555/// the `---` terminator to end of file and blanks the entire body,
556/// markers and all — a conflicted file would then load with both
557/// sides fused into one entity, which is precisely the outcome
558/// `entity::loader`'s caller exists to prevent. Git also writes
559/// conflict markers into frontmatter, so scanning it is not merely
560/// safe, it is required.
561pub fn has_merge_conflict_markers(text: &str) -> bool {
562 // One view, not two scans: a conflict can straddle the `---`
563 // terminator (git writes markers wherever the hunks fall), so the
564 // raw frontmatter and the masked body are rejoined and scanned as
565 // a single text. Masking preserves byte length, so the join is the
566 // original file with only body code blocks blanked.
567 let body = body_after_frontmatter(text);
568 let frontmatter = &text[..text.len() - body.len()];
569 let view = format!("{frontmatter}{}", mask_code_blocks(body));
570
571 let mut seen_start = false;
572 let mut seen_separator = false;
573 for line in view.lines() {
574 if line.starts_with("<<<<<<< ") {
575 seen_start = true;
576 seen_separator = false;
577 } else if seen_start && line.trim_end() == "=======" {
578 seen_separator = true;
579 } else if seen_separator && line.starts_with(">>>>>>> ") {
580 return true;
581 }
582 }
583 false
584}
585
586// ---------------------------------------------------------------------------
587// Section splitting
588// ---------------------------------------------------------------------------
589
590/// Tracks one schema-declared section key seen more than once on parse.
591/// `key` is the slugified storage key (e.g. `realization`); `heading` is
592/// the original literal text from the first occurrence (e.g. `Realization`).
593/// Sections keyed by derived key; each value is the heading line
594/// VERBATIM from the original body plus the section's content.
595pub(crate) type SplitSections = IndexMap<String, (String, String)>;
596
597/// `occurrences` counts every header line for that key — first plus
598/// duplicates.
599pub(crate) struct DuplicateSection {
600 pub key: String,
601 pub heading: String,
602 pub occurrences: usize,
603}
604
605/// The section boundary: a column-0 ATX `## ` line with a non-empty
606/// rest, matched over a MASKED text. One definition, used over the
607/// whole body and again over each piece the splitter reads from a
608/// neutral start.
609fn section_heading_re() -> &'static Regex {
610 static RE: OnceLock<Regex> = OnceLock::new();
611 RE.get_or_init(|| Regex::new(r"(?m)^## (.+)$").unwrap())
612}
613
614/// A section's stored content and the body offset where it starts.
615///
616/// Leading trim drops blank lines wholesale but keeps the first
617/// visible line's indentation: a full trim promoted an indented
618/// heading-lookalike (` ## Specifies`) to column 0 inside stored
619/// content, where the catch-all re-emit made the NEXT parse read
620/// it as a real section heading — structure from content, and a
621/// broken parse-generate fixpoint (fuzz finding, long tier,
622/// 2026-08-24, corpus member `crash-de0c69e0…`). Trailing trim
623/// stays full: it can never move a line to column 0. The
624/// runtime validator's embedded-heading guard keeps its own full
625/// trim, so the mutation path refuses exactly what it refused.
626fn section_content(body: &str, content_start: usize, content_end: usize) -> (&str, usize) {
627 let raw = &body[content_start..content_end];
628 let visible_start = raw
629 .split_inclusive('\n')
630 .take_while(|line| line.trim().is_empty())
631 .map(str::len)
632 .sum::<usize>();
633 (
634 raw[visible_start..].trim_end(),
635 content_start + visible_start,
636 )
637}
638
639/// Every section boundary of `body` in document order, each the byte
640/// range of its heading line.
641///
642/// The first pass is the regex over the masked body: a column-0 `## `
643/// line outside every code block. That pass reads each heading where
644/// it stands, and a heading can stand inside a block the referee is
645/// still reading: an HTML block of a kind no blank line ends (`<!X`,
646/// `<!--`, `<?`), or a table. The splitter does not narrow the
647/// boundary there (a `## ` line inside an unterminated comment stays a
648/// section, so a stray `<!--` never swallows the rest of the document),
649/// but the section's content was then read in situ under that block's
650/// context, and the generator writes every section from a neutral
651/// start: heading line, newline, content. Read from there the same
652/// bytes can mean something else. A `<!--` that was inert inside a
653/// `<!X` block opens a comment, the tilde fence after it goes dead, and
654/// a `## ` line the fence masked in situ reads as a heading on the next
655/// parse; the second parse splits where the first did not and the two
656/// generations differ (fuzz findings, CI runs 2026-09-08 and
657/// 2026-09-09, corpus members `crash-c9e7bbf7…` and `crash-ce631bf5…`;
658/// in the first the enclosing block was opened by the preceding
659/// section, in the second by the preamble before any heading, so no
660/// rule about closers between merged pieces can repair the class).
661///
662/// So the second pass reads every such section the way the generator
663/// will write it. A heading the referee did not itself read as a
664/// heading in situ was read inside some other block; its piece
665/// (verbatim heading line, newline, trimmed content) is masked from a
666/// neutral start, and the first `## ` line that surfaces becomes a
667/// boundary of its own. The new piece is read the same way, and so on
668/// until every piece shows exactly one boundary. Boundaries are only
669/// ever added, and only at lines the next parse would have split on
670/// anyway, so the first parse already lands on the fixpoint. A section
671/// whose heading the referee read as a heading stands in a neutral
672/// context already (a column-0 ATX heading ends every paragraph, list
673/// and quote before it, and a code block would have masked it), so its
674/// in-situ reading and the generator's agree; reading it again would
675/// find nothing, which is why the heading list is only a cost filter
676/// and most documents never enter the second pass.
677fn section_boundaries(body: &str, masked_body: &str) -> Vec<Range<usize>> {
678 let mut bounds: BTreeMap<usize, usize> = section_heading_re()
679 .find_iter(masked_body)
680 .map(|m| (m.start(), m.end()))
681 .collect();
682 if bounds.is_empty() {
683 return Vec::new();
684 }
685 let read_as_heading = crate::markdown::heading_starts(body);
686 let mut work: Vec<usize> = bounds
687 .keys()
688 .copied()
689 .filter(|start| read_as_heading.binary_search(start).is_err())
690 .collect();
691 while let Some(start) = work.pop() {
692 let end = bounds[&start];
693 let content_end = bounds
694 .range(start + 1..)
695 .next()
696 .map_or(body.len(), |(next, _)| *next);
697 let heading_line = &body[start..end];
698 let (content, content_start) = section_content(body, end, content_end);
699 let piece = format!("{heading_line}\n{content}");
700 let masked = mask_code_blocks(&piece);
701 let Some(extra) = section_heading_re()
702 .find_iter(&masked)
703 .find(|m| m.start() > 0)
704 else {
705 continue;
706 };
707 // The piece is heading line, `\n`, content: an offset past the
708 // heading line maps into the body at the content's start.
709 let abs_start = content_start + (extra.start() - heading_line.len() - 1);
710 bounds.insert(abs_start, abs_start + extra.len());
711 work.push(abs_start);
712 }
713 bounds.into_iter().map(|(start, end)| start..end).collect()
714}
715
716/// Split body into named sections. Returns `Map<lowercase_key,
717/// (heading_line, content)>` — the heading line VERBATIM from the
718/// original body, because the catch-all re-emits it and a heading
719/// rebuilt from the derived key changes what the CommonMark referee
720/// sees (a CR inside a heading is a line ending of its own, so its
721/// tail can be a live fence opener; the derived key lost the CRs, the
722/// re-parse un-masked the section's content, and a promoted empty
723/// heading then vanished — fuzz finding, corpus member
724/// `crash-9fd95247…`) — plus a list of duplicate-heading occurrences.
725/// Duplicate headings keep the first occurrence's body; subsequent
726/// occurrences are dropped from the storage value entirely (no
727/// embedded `## Heading` separator). The caller decides whether each
728/// duplicate becomes a `WarningHint` (schema-declared keys only —
729/// catch-all repetition stays silent). The third element is every
730/// literal heading text in document order (duplicates included) — the
731/// raw material for the health check that distinguishes "section
732/// absent" from "content under a non-deriving heading".
733pub(crate) fn split_sections(
734 body: &str,
735 masked_body: &str,
736) -> (SplitSections, Vec<DuplicateSection>, Vec<String>) {
737 // IndexMap, not HashMap: the catch-all builder re-emits non-schema
738 // sections in this map's iteration order, so the order must be the
739 // document's — hash-random order made canonical bytes unstable
740 // across parses whenever more than one non-schema section coexisted
741 // (reachable on the tolerant local-read path, which refuses nothing).
742 let mut sections = IndexMap::new();
743 let mut duplicates: HashMap<String, DuplicateSection> = HashMap::new();
744 let mut raw_headings = Vec::new();
745 let boundaries = section_boundaries(body, masked_body);
746
747 for (i, m) in boundaries.iter().enumerate() {
748 // Extract heading name from original body (not masked)
749 let heading_line = &body[m.clone()];
750 let name = heading_line
751 .strip_prefix("## ")
752 .unwrap_or(heading_line)
753 .trim();
754
755 let content_end = boundaries.get(i + 1).map_or(body.len(), |next| next.start);
756 let (content, _) = section_content(body, m.end, content_end);
757 let content = content.to_string();
758 // Schema section keys are underscore-separated (e.g. `current_state`).
759 // A heading like `## Current State` must derive to the same form so
760 // schema-declared sections land in `result_sections` under the right
761 // key instead of falling through to catch-all — which would break
762 // canonical byte-stability for any multi-word section. The derivation
763 // is shared with the schema loader's round-trip check — never inline
764 // a second copy here.
765 let key = memstead_schema::derive_section_key(name);
766 raw_headings.push(name.to_string());
767
768 match sections.entry(key.clone()) {
769 indexmap::map::Entry::Vacant(slot) => {
770 slot.insert((heading_line.to_string(), content));
771 duplicates.insert(
772 key.clone(),
773 DuplicateSection {
774 key: key.clone(),
775 heading: name.to_string(),
776 occurrences: 1,
777 },
778 );
779 }
780 indexmap::map::Entry::Occupied(_) => {
781 // First-wins: drop this duplicate's body entirely. Bump the
782 // occurrence count for the warning emitted by the caller.
783 if let Some(d) = duplicates.get_mut(&key) {
784 d.occurrences += 1;
785 }
786 }
787 }
788 }
789
790 let dup_list: Vec<DuplicateSection> = duplicates
791 .into_values()
792 .filter(|d| d.occurrences > 1)
793 .collect();
794
795 (sections, dup_list, raw_headings)
796}
797
798/// Extract the title from the first `# ` heading.
799///
800/// Scans the masked body so a `# ` line inside a code block can never
801/// become the entity title, and reads the text back from the original —
802/// masking preserves byte offsets and line count, so the two line
803/// sequences correspond one-to-one.
804fn extract_title(body: &str, masked_body: &str) -> Option<String> {
805 for (line, masked) in body.lines().zip(masked_body.lines()) {
806 if masked.starts_with("# ") {
807 return Some(line[2..].trim().to_string());
808 }
809 }
810 None
811}
812
813// ---------------------------------------------------------------------------
814// Heading spans (H3–H6)
815// ---------------------------------------------------------------------------
816
817/// Extract H3–H6 heading spans from each section's content. Byte offsets are
818/// into the (trimmed) section string stored in `result_sections`. Code blocks
819/// are masked before scanning so `### foo` inside any code block is ignored.
820///
821/// End offsets use a level-aware closing rule: a span closes at the next
822/// heading with the same or lower level (H3 closes on next H3 or H2 — but
823/// H2 doesn't appear here since sections are already split), otherwise at
824/// the end of the section. Level skips (H2 → H4 without H3) are tolerated:
825/// the H4 span is recorded flat, and query-time path resolution uses offset
826/// containment to reconstruct ancestry.
827fn extract_heading_spans(sections: &IndexMap<String, String>) -> HashMap<String, Vec<HeadingSpan>> {
828 // Compiled once per process; shape-constrained so it can't fail at runtime.
829 static RE: OnceLock<Regex> = OnceLock::new();
830 let re = RE.get_or_init(|| Regex::new(r"(?m)^(#{3,6})[ \t]+(.+)$").unwrap());
831 let mut out: HashMap<String, Vec<HeadingSpan>> = HashMap::new();
832
833 for (key, content) in sections {
834 if content.is_empty() {
835 continue;
836 }
837 let masked = mask_code_blocks(content);
838
839 // Collect (start_offset, level, title) in document order.
840 let raw: Vec<(usize, u8, String)> = re
841 .captures_iter(&masked)
842 .map(|cap| {
843 let whole = cap.get(0).unwrap();
844 let level = cap[1].len() as u8; // 3..=6
845 // Read the title from the original (unmasked) content so the
846 // captured text survives code-block masking's space-padding.
847 let line_end = content[whole.start()..]
848 .find('\n')
849 .map(|i| whole.start() + i)
850 .unwrap_or(content.len());
851 let hashes_end = whole.start() + level as usize;
852 let title = content[hashes_end..line_end].trim().to_string();
853 (whole.start(), level, title)
854 })
855 .collect();
856
857 if raw.is_empty() {
858 continue;
859 }
860
861 let mut spans: Vec<HeadingSpan> = Vec::with_capacity(raw.len());
862 for (i, &(start, level, ref title)) in raw.iter().enumerate() {
863 // Scan forward for the next heading with level <= this one.
864 let end = raw[i + 1..]
865 .iter()
866 .find(|(_, l, _)| *l <= level)
867 .map(|(s, _, _)| *s)
868 .unwrap_or(content.len());
869 spans.push(HeadingSpan {
870 level,
871 title: title.clone(),
872 start_offset: start,
873 end_offset: end,
874 });
875 }
876 out.insert(key.clone(), spans);
877 }
878
879 out
880}
881
882// ---------------------------------------------------------------------------
883// Catch-all section
884// ---------------------------------------------------------------------------
885
886/// Build catch-all section content from its own section + non-schema sections.
887fn build_catch_all(sections: &SplitSections, schema: &TypeDefinition) -> String {
888 let catch_all = match schema.catch_all_section() {
889 Some(s) => s,
890 None => return String::new(),
891 };
892
893 let known_sections: HashSet<&str> = schema
894 .sections
895 .iter()
896 .map(|s| s.key.as_str())
897 .chain(std::iter::once("relationships"))
898 .collect();
899
900 let mut parts = Vec::new();
901
902 // First, add the explicit catch-all section content
903 if let Some((_, content)) = sections.get(catch_all.key.as_str())
904 && !content.is_empty()
905 {
906 parts.push(content.clone());
907 }
908
909 // Then add all non-schema sections, each re-emitted under its
910 // ORIGINAL heading line, byte-verbatim — never a heading rebuilt
911 // from the derived key: the rebuilt form changed what the referee
912 // sees (a CR inside a heading is a CommonMark line ending of its
913 // own, so its tail can be a live fence opener the derived key
914 // lost), and the re-parse then promoted masked content to
915 // structure (fuzz finding, corpus member `crash-9fd95247…`).
916 // Document order — `sections` is an IndexMap for exactly this
917 // loop: with more than one non-schema section (reachable on the
918 // tolerant local-read path, which refuses nothing) a hash-random
919 // order made the reconstructed catch-all differ from parse to parse.
920 for (key, (heading_line, content)) in sections {
921 if !known_sections.contains(key.as_str()) && !content.is_empty() {
922 parts.push(format!("{heading_line}\n{content}"));
923 }
924 }
925
926 // Incremental context close: every close decision is judged over
927 // the RUNNING string after each append — never over a piece in
928 // isolation. Isolation misjudges in both directions (lazy
929 // continuation and CR line endings make the same bytes a fence in
930 // one context and prose in another): an isolation close injected a
931 // spurious closer that the generator's part-level close then paired
932 // into an empty fence block, growing the document every round
933 // (corpus candidate `crash-619fe90c`), while skipping the close
934 // entirely let a piece's dangling fence swallow the next piece's
935 // heading (corpus member `crash-07c152bb`). Closing in context
936 // after each piece keeps both: a dangling fence closes before the
937 // next piece, and no closer is ever added for a construct the
938 // document context does not read as a fence. The oracle verifies
939 // its closer against the mask, so the appended line is a real
940 // closer wherever it lands. The context is not only fences: an
941 // HTML block of the kinds no blank line ends (`<!X`, `<!--`, `<?`,
942 // `<![CDATA[`, a `<script>`-family tag) hides every fence the
943 // referee would otherwise read, so a piece that ends inside one
944 // changes what the NEXT piece's fences mean — a `## ` line that a
945 // fence masked in situ surfaces as a heading after the merge, and
946 // as an empty non-schema section it is dropped a round later
947 // (fuzz finding, long tier, 0.17.0 release readiness run, corpus
948 // member `crash-1233c134…`). The same oracle closes both.
949 //
950 // A closer between two pieces is always safe to write: every piece
951 // reads as exactly one section from a neutral start
952 // (`section_boundaries` guarantees it, reading each section the
953 // way it is written here), and the verified closer leaves exactly
954 // that start for the next piece. The mirror case, a closer that
955 // changed how the next piece read because that piece had been read
956 // inside a block the previous one left open, is settled at the
957 // splitter, not judged here (fuzz findings, corpus members
958 // `crash-c9e7bbf7…` and `crash-ce631bf5…`).
959 let mut joined = String::new();
960 for piece in parts {
961 if joined.is_empty() {
962 joined = piece;
963 } else {
964 joined.push_str("\n\n");
965 joined.push_str(&piece);
966 }
967 if let Some(closer) = crate::markdown::closing_context_if_unterminated(&joined) {
968 joined.push('\n');
969 joined.push_str(&closer);
970 }
971 }
972 joined
973}
974
975// ---------------------------------------------------------------------------
976// Relationships
977// ---------------------------------------------------------------------------
978
979/// Parse typed relationships from the Relationships section.
980///
981/// Recognises two row shapes:
982/// - simple: `- **TYPE**: [[target]]` → `description: None`
983/// - em-dash: `- **TYPE**: [[target]] — text` → `description: Some(text)`
984///
985/// Returns the relations plus parse-time warnings flagging
986/// AMBIGUOUS-delimiter rows (`-- text`, `- text`, en-dash, minus). On
987/// AMBIGUOUS rows the description is dropped — the renderer will
988/// normalise the row to the simple form on next write.
989///
990/// Rows inside a code block are not relationships. The scan runs over
991/// the masked section body and reads every captured span from the
992/// original, so a fenced or indented example of the row syntax — the
993/// obvious thing to write in an entity documenting that syntax — no
994/// longer becomes a live edge and an auto-stub. Without the mask this
995/// path synthesised edges from links the strict validator cannot see
996/// (`validator::strict::check_wiki_links` masks), which is exactly the
997/// asymmetry the one-definition rule exists to prevent.
998pub(crate) fn parse_relationships_with_warnings(
999 text: &str,
1000 mem: &str,
1001 entity_id: Option<&EntityId>,
1002) -> (Vec<Relationship>, Vec<crate::ops::WarningHint>) {
1003 // Anchor on the canonical row prefix `- **TYPE**: [[<target>]]` and
1004 // capture everything that follows on the same line so the trailing
1005 // segment can be classified (simple, em-dash, or AMBIGUOUS).
1006 //
1007 // The target must not cross a line: a ROW is a line. A capture
1008 // spanning a newline only ever came from degenerate drift, and it
1009 // cannot round-trip — the generated multi-line token re-enters the
1010 // mask with different structure (a following `-` + tab line reads
1011 // as list-item indented code and swallows the closing `]]`), so
1012 // the row silently vanished one round later (fuzz finding, corpus
1013 // member `crash-93f0a4bd…`). Ids containing newlines can never
1014 // exist as entity files, so such pseudo-rows are consistently not
1015 // relationships in ANY round.
1016 static RE: OnceLock<Regex> = OnceLock::new();
1017 let re = RE.get_or_init(|| {
1018 Regex::new(r"(?m)^\s*-\s*\*\*(\w+)\*\*:\s*\[\[([^\]\n]+)\]\](?P<tail>[^\n]*)").unwrap()
1019 });
1020 let mut relationships = Vec::new();
1021 let mut warnings = Vec::new();
1022 // Blocks AND inline spans — the same mask every link scanner uses.
1023 // A legitimate row's target can never sit inside a code span, so
1024 // masking spans costs nothing and closes the seam: with a
1025 // blocks-only mask a row inside a multi-line inline span stayed
1026 // invisible to the validator and to every extractor while still
1027 // building an edge and a stub. Masking preserves byte offsets, so a
1028 // match found in the masked copy indexes the original exactly.
1029 let masked = mask_code_blocks_and_spans(text);
1030 for cap in re.captures_iter(&masked) {
1031 let rel_type = text[cap.get(1).unwrap().range()].to_uppercase();
1032 // Read-time parsing of the ## Relationships table tolerates
1033 // pre-strict on-disk drift so legacy rows whose target fails
1034 // the wiki-link grammar continue to round-trip. The mutation
1035 // pipeline (`memstead_relate`, declare_relations) gates strictly
1036 // via `validate_relation_target_grammar`.
1037 let target = wiki_link_to_id_lenient(&text[cap.get(2).unwrap().range()], mem);
1038 // A raw target that decodes to an EMPTY path (`[[specs--]]`
1039 // after the self-prefix strip, `[[../]]` after decoration
1040 // stripping) is not a relationship: the generator would render
1041 // it as `[[]]`, which the row pattern cannot re-capture, so the
1042 // row silently vanished one round later (fuzz finding, corpus
1043 // member `crash-0c7207a1…`). Skipping it here mirrors how rows
1044 // that never match the pattern behave; both strict gates refuse
1045 // such targets outright.
1046 if target.path().is_empty() {
1047 continue;
1048 }
1049 let tail = cap.name("tail").map(|m| &text[m.range()]).unwrap_or("");
1050 let description = match classify_description_tail(tail) {
1051 DescriptionTail::None => None,
1052 DescriptionTail::EmDash(text) => Some(text),
1053 DescriptionTail::Ambiguous(literal) => {
1054 if let Some(id) = entity_id {
1055 warnings.push(crate::ops::WarningHint::AmbiguousDescriptionDelimiter {
1056 from: id.clone(),
1057 rel_type: rel_type.clone(),
1058 target: target.clone(),
1059 trailing: literal,
1060 });
1061 }
1062 None
1063 }
1064 };
1065 relationships.push(Relationship {
1066 rel_type,
1067 target,
1068 description,
1069 });
1070 }
1071 (relationships, warnings)
1072}
1073
1074/// Classification of the per-line tail that follows `]]` on a
1075/// `## Relationships` row.
1076enum DescriptionTail {
1077 /// Tail is empty or whitespace-only.
1078 None,
1079 /// Tail begins with the canonical em-dash delimiter; carries the
1080 /// captured description text (trimmed of trailing whitespace).
1081 EmDash(String),
1082 /// Tail starts with a non-canonical dash-like delimiter (`-`,
1083 /// `--`, U+2013 en-dash, U+2212 minus). Carries the literal
1084 /// trailing content so the warning surfaces what was dropped.
1085 Ambiguous(String),
1086}
1087
1088/// Inspect the post-`]]` tail of a `## Relationships` row and decide
1089/// what shape it takes. The em-dash delimiter is the exact three-byte
1090/// UTF-8 sequence of U+2014 framed by single ASCII spaces; everything
1091/// else falls into [`DescriptionTail::None`] or
1092/// [`DescriptionTail::Ambiguous`].
1093fn classify_description_tail(tail: &str) -> DescriptionTail {
1094 let trimmed_end = tail.trim_end();
1095 if trimmed_end.is_empty() {
1096 return DescriptionTail::None;
1097 }
1098 // Canonical: literal space + U+2014 + literal space + content.
1099 if let Some(rest) = trimmed_end.strip_prefix(" \u{2014} ") {
1100 if rest.is_empty() {
1101 return DescriptionTail::None;
1102 }
1103 return DescriptionTail::EmDash(rest.to_string());
1104 }
1105 // U+2014 directly after `]]` (no leading space) is also ambiguous
1106 // — the canonical form requires the framing space. Likewise an
1107 // em-dash with no trailing content (` — `) collapses to None.
1108 if let Some(rest) = trimmed_end.strip_prefix(" \u{2014}") {
1109 // ` —` (no trailing space, but content followed) lands here.
1110 return DescriptionTail::Ambiguous(format!(" \u{2014}{rest}"));
1111 }
1112 // Dash-likes: ASCII `--`, ASCII `-`, en-dash U+2013, minus U+2212.
1113 let starters = [" --", " -", " \u{2013}", " \u{2212}"];
1114 if starters
1115 .iter()
1116 .any(|prefix| trimmed_end.starts_with(prefix))
1117 {
1118 return DescriptionTail::Ambiguous(trimmed_end.to_string());
1119 }
1120 // Anything else after `]]` (e.g. inline comment, stray text) —
1121 // classify as ambiguous so the operator sees that content was
1122 // dropped rather than silently swallowed.
1123 DescriptionTail::Ambiguous(trimmed_end.to_string())
1124}
1125
1126// ---------------------------------------------------------------------------
1127// Wiki-links
1128// ---------------------------------------------------------------------------
1129
1130/// The `[[target]]` / `[[target|label]]` wiki-link pattern, compiled once.
1131///
1132/// The inner group is `*`, not `+`, so an empty target `[[]]` is *seen*
1133/// by every path — the strict validator refuses it with a typed
1134/// `InvalidWikiLink`, and this module's strict extractor routes it to
1135/// the same refusal. A pattern that cannot see `[[]]` is how one path
1136/// came to silently ignore what another path refused.
1137fn wiki_link_re() -> &'static Regex {
1138 static RE: OnceLock<Regex> = OnceLock::new();
1139 RE.get_or_init(|| Regex::new(r"\[\[([^\]]*)\]\]").unwrap())
1140}
1141
1142/// Extract unique mem-prefixed entity IDs from inline wiki-links,
1143/// strictly validating each target against the slug-form grammar.
1144/// Strips code blocks and inline code spans before scanning, by the
1145/// one CommonMark definition ([`crate::markdown`]).
1146///
1147/// Returns the deduped valid ids on success, or every refusal in the
1148/// scan window on failure (errors are collected, not fail-fast — the
1149/// agent sees every malformed link in a single round-trip).
1150///
1151/// Mutation-pipeline callers (`synthesise_alias_relations`, etc.) use
1152/// this strict variant and map [`WikiLinkError`] to the typed engine
1153/// envelope with section context. Read-side scanners that must
1154/// tolerate pre-strict on-disk drift use [`extract_inline_links_lenient`].
1155pub(crate) fn extract_inline_links(
1156 text: &str,
1157 mem: &str,
1158) -> Result<Vec<EntityId>, Vec<WikiLinkError>> {
1159 let stripped = mask_code_blocks_and_spans(text);
1160
1161 let link_re = wiki_link_re();
1162 let mut seen = HashSet::new();
1163 let mut links = Vec::new();
1164 let mut errors = Vec::new();
1165
1166 for cap in link_re.captures_iter(&stripped) {
1167 match wiki_link_to_id(&cap[1], mem) {
1168 Ok(id) => {
1169 if errors.is_empty() && seen.insert(id.0.clone()) {
1170 links.push(id);
1171 }
1172 }
1173 Err(e) => errors.push(e),
1174 }
1175 }
1176
1177 if errors.is_empty() {
1178 Ok(links)
1179 } else {
1180 Err(errors)
1181 }
1182}
1183
1184/// Permissive sibling of [`extract_inline_links`] for read-side
1185/// scanners. Decodes every `[[...]]` token via [`wiki_link_to_id_lenient`]
1186/// so on-disk drift (legacy entities, archive-imports from pre-strict
1187/// engines, partial-mutation rollbacks) keeps flowing through dangling-
1188/// link reporters and graph inspectors. Mutation paths MUST NOT use this
1189/// helper — see [`extract_inline_links`] for the strict variant.
1190pub fn extract_inline_links_lenient(text: &str, mem: &str) -> Vec<EntityId> {
1191 let stripped = mask_code_blocks_and_spans(text);
1192
1193 let link_re = wiki_link_re();
1194 let mut seen = HashSet::new();
1195 let mut links = Vec::new();
1196
1197 for cap in link_re.captures_iter(&stripped) {
1198 // An empty target decodes to no id. The read side tolerates
1199 // drift by ignoring what it cannot decode; the strict side
1200 // refuses it (`extract_inline_links`). Both *see* it — that is
1201 // the part that must not diverge.
1202 if cap[1].is_empty() {
1203 continue;
1204 }
1205 let id = wiki_link_to_id_lenient(&cap[1], mem);
1206 if seen.insert(id.0.clone()) {
1207 links.push(id);
1208 }
1209 }
1210
1211 links
1212}
1213
1214// ---------------------------------------------------------------------------
1215// Content hash
1216// ---------------------------------------------------------------------------
1217
1218/// Compute SHA-256 hash of content, truncated to 16 hex characters.
1219pub fn compute_hash(content: &str) -> String {
1220 let mut hasher = Sha256::new();
1221 hasher.update(content.as_bytes());
1222 let result = hasher.finalize();
1223 crate::hex_lower(&result)[..16].to_string()
1224}
1225
1226// ---------------------------------------------------------------------------
1227// Errors
1228// ---------------------------------------------------------------------------
1229
1230#[derive(Debug, thiserror::Error)]
1231pub enum ParseError {
1232 #[error("missing frontmatter")]
1233 MissingFrontmatter,
1234 #[error("invalid frontmatter: {0}")]
1235 InvalidFrontmatter(String),
1236 #[error("missing title")]
1237 MissingTitle,
1238 #[error("io error: {0}")]
1239 Io(#[from] std::io::Error),
1240}
1241
1242/// End-to-end pins for the six verified code-block misparse classes,
1243/// on the real entity paths: section splitting, title extraction,
1244/// heading spans, and wiki-link extraction. The unit-level pins for
1245/// the mask itself live in [`crate::markdown`]; these assert the
1246/// classes are actually fixed where they did damage.
1247#[cfg(test)]
1248mod commonmark_referee;
1249
1250#[cfg(test)]
1251mod tests;