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