1use 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
22pub 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 let content_hash = compute_hash(content);
33
34 let (metadata, body) = split_frontmatter(content)?;
40 let masked_body = mask_code_blocks(&body);
41
42 let title = extract_title(&body, &masked_body).unwrap_or_else(|| id.name().to_string());
44
45 let (sections_map, duplicate_headings, raw_section_headings) =
50 split_sections(&body, &masked_body);
51
52 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 let catch_all_content = build_catch_all(§ions_map, schema);
70
71 let mut result_sections = IndexMap::new();
83 for s in &schema.sections {
84 if s.catch_all {
85 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 }
103
104 let mut parsed_metadata = parse_metadata(&metadata);
106
107 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 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 let inline_links = extract_inline_links_lenient(&inline_link_text, mem);
131
132 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 let heading_spans = extract_heading_spans(&result_sections);
142
143 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
188pub 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#[derive(Debug, PartialEq, Eq)]
216pub enum Frontmatter<'a> {
217 Present { meta: &'a str, body: &'a str },
219 NoOpeningDelimiter,
221 Unclosed,
223}
224
225pub 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
263pub 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
277pub 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
316pub 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
331pub fn body_after_frontmatter(content: &str) -> &str {
347 match split_frontmatter_core(content) {
348 (_, Frontmatter::Present { body, .. }) => body,
349 (stripped, _) => stripped,
350 }
351}
352
353pub(crate) fn split_frontmatter(content: &str) -> Result<(String, String), ParseError> {
357 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
366fn 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 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 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 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
423fn 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
436fn 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
442pub(crate) fn would_coerce_from_string(s: &str) -> bool {
448 s == "true" || s == "false" || is_integer_literal(s) || is_float_literal(s)
449}
450
451fn strip_inline_comment(s: &str) -> &str {
453 if let Some(idx) = s.find(" #") {
456 s[..idx].trim_end()
457 } else {
458 s
459 }
460}
461
462fn strip_quotes(s: &str) -> String {
466 if s.len() >= 2
467 && ((s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')))
468 {
469 s[1..s.len() - 1].to_string()
470 } else {
471 s.to_string()
472 }
473}
474
475pub use crate::markdown::{mask_code_blocks, mask_code_blocks_and_spans};
487
488pub fn has_merge_conflict_markers(text: &str) -> bool {
518 let body = body_after_frontmatter(text);
524 let frontmatter = &text[..text.len() - body.len()];
525 let view = format!("{frontmatter}{}", mask_code_blocks(body));
526
527 let mut seen_start = false;
528 let mut seen_separator = false;
529 for line in view.lines() {
530 if line.starts_with("<<<<<<< ") {
531 seen_start = true;
532 seen_separator = false;
533 } else if seen_start && line.trim_end() == "=======" {
534 seen_separator = true;
535 } else if seen_separator && line.starts_with(">>>>>>> ") {
536 return true;
537 }
538 }
539 false
540}
541
542pub(crate) type SplitSections = IndexMap<String, (String, String)>;
552
553pub(crate) struct DuplicateSection {
556 pub key: String,
557 pub heading: String,
558 pub occurrences: usize,
559}
560
561fn section_heading_re() -> &'static Regex {
566 static RE: OnceLock<Regex> = OnceLock::new();
567 RE.get_or_init(|| Regex::new(r"(?m)^## (.+)$").unwrap())
568}
569
570fn section_content(body: &str, content_start: usize, content_end: usize) -> (&str, usize) {
583 let raw = &body[content_start..content_end];
584 let visible_start = raw
585 .split_inclusive('\n')
586 .take_while(|line| line.trim().is_empty())
587 .map(str::len)
588 .sum::<usize>();
589 (
590 raw[visible_start..].trim_end(),
591 content_start + visible_start,
592 )
593}
594
595fn section_boundaries(body: &str, masked_body: &str) -> Vec<Range<usize>> {
634 let mut bounds: BTreeMap<usize, usize> = section_heading_re()
635 .find_iter(masked_body)
636 .map(|m| (m.start(), m.end()))
637 .collect();
638 if bounds.is_empty() {
639 return Vec::new();
640 }
641 let read_as_heading = crate::markdown::heading_starts(body);
642 let mut work: Vec<usize> = bounds
643 .keys()
644 .copied()
645 .filter(|start| read_as_heading.binary_search(start).is_err())
646 .collect();
647 while let Some(start) = work.pop() {
648 let end = bounds[&start];
649 let content_end = bounds
650 .range(start + 1..)
651 .next()
652 .map_or(body.len(), |(next, _)| *next);
653 let heading_line = &body[start..end];
654 let (content, content_start) = section_content(body, end, content_end);
655 let piece = format!("{heading_line}\n{content}");
656 let masked = mask_code_blocks(&piece);
657 let Some(extra) = section_heading_re()
658 .find_iter(&masked)
659 .find(|m| m.start() > 0)
660 else {
661 continue;
662 };
663 let abs_start = content_start + (extra.start() - heading_line.len() - 1);
666 bounds.insert(abs_start, abs_start + extra.len());
667 work.push(abs_start);
668 }
669 bounds.into_iter().map(|(start, end)| start..end).collect()
670}
671
672pub(crate) fn split_sections(
690 body: &str,
691 masked_body: &str,
692) -> (SplitSections, Vec<DuplicateSection>, Vec<String>) {
693 let mut sections = IndexMap::new();
699 let mut duplicates: HashMap<String, DuplicateSection> = HashMap::new();
700 let mut raw_headings = Vec::new();
701 let boundaries = section_boundaries(body, masked_body);
702
703 for (i, m) in boundaries.iter().enumerate() {
704 let heading_line = &body[m.clone()];
706 let name = heading_line
707 .strip_prefix("## ")
708 .unwrap_or(heading_line)
709 .trim();
710
711 let content_end = boundaries.get(i + 1).map_or(body.len(), |next| next.start);
712 let (content, _) = section_content(body, m.end, content_end);
713 let content = content.to_string();
714 let key = memstead_schema::derive_section_key(name);
722 raw_headings.push(name.to_string());
723
724 match sections.entry(key.clone()) {
725 indexmap::map::Entry::Vacant(slot) => {
726 slot.insert((heading_line.to_string(), content));
727 duplicates.insert(
728 key.clone(),
729 DuplicateSection {
730 key: key.clone(),
731 heading: name.to_string(),
732 occurrences: 1,
733 },
734 );
735 }
736 indexmap::map::Entry::Occupied(_) => {
737 if let Some(d) = duplicates.get_mut(&key) {
740 d.occurrences += 1;
741 }
742 }
743 }
744 }
745
746 let dup_list: Vec<DuplicateSection> = duplicates
747 .into_values()
748 .filter(|d| d.occurrences > 1)
749 .collect();
750
751 (sections, dup_list, raw_headings)
752}
753
754fn extract_title(body: &str, masked_body: &str) -> Option<String> {
761 for (line, masked) in body.lines().zip(masked_body.lines()) {
762 if masked.starts_with("# ") {
763 return Some(line[2..].trim().to_string());
764 }
765 }
766 None
767}
768
769fn extract_heading_spans(sections: &IndexMap<String, String>) -> HashMap<String, Vec<HeadingSpan>> {
784 static RE: OnceLock<Regex> = OnceLock::new();
786 let re = RE.get_or_init(|| Regex::new(r"(?m)^(#{3,6})[ \t]+(.+)$").unwrap());
787 let mut out: HashMap<String, Vec<HeadingSpan>> = HashMap::new();
788
789 for (key, content) in sections {
790 if content.is_empty() {
791 continue;
792 }
793 let masked = mask_code_blocks(content);
794
795 let raw: Vec<(usize, u8, String)> = re
797 .captures_iter(&masked)
798 .map(|cap| {
799 let whole = cap.get(0).unwrap();
800 let level = cap[1].len() as u8; let line_end = content[whole.start()..]
804 .find('\n')
805 .map(|i| whole.start() + i)
806 .unwrap_or(content.len());
807 let hashes_end = whole.start() + level as usize;
808 let title = content[hashes_end..line_end].trim().to_string();
809 (whole.start(), level, title)
810 })
811 .collect();
812
813 if raw.is_empty() {
814 continue;
815 }
816
817 let mut spans: Vec<HeadingSpan> = Vec::with_capacity(raw.len());
818 for (i, &(start, level, ref title)) in raw.iter().enumerate() {
819 let end = raw[i + 1..]
821 .iter()
822 .find(|(_, l, _)| *l <= level)
823 .map(|(s, _, _)| *s)
824 .unwrap_or(content.len());
825 spans.push(HeadingSpan {
826 level,
827 title: title.clone(),
828 start_offset: start,
829 end_offset: end,
830 });
831 }
832 out.insert(key.clone(), spans);
833 }
834
835 out
836}
837
838fn build_catch_all(sections: &SplitSections, schema: &TypeDefinition) -> String {
844 let catch_all = match schema.catch_all_section() {
845 Some(s) => s,
846 None => return String::new(),
847 };
848
849 let known_sections: HashSet<&str> = schema
850 .sections
851 .iter()
852 .map(|s| s.key.as_str())
853 .chain(std::iter::once("relationships"))
854 .collect();
855
856 let mut parts = Vec::new();
857
858 if let Some((_, content)) = sections.get(catch_all.key.as_str())
860 && !content.is_empty()
861 {
862 parts.push(content.clone());
863 }
864
865 for (key, (heading_line, content)) in sections {
877 if !known_sections.contains(key.as_str()) && !content.is_empty() {
878 parts.push(format!("{heading_line}\n{content}"));
879 }
880 }
881
882 let mut joined = String::new();
916 for piece in parts {
917 if joined.is_empty() {
918 joined = piece;
919 } else {
920 joined.push_str("\n\n");
921 joined.push_str(&piece);
922 }
923 if let Some(closer) = crate::markdown::closing_context_if_unterminated(&joined) {
924 joined.push('\n');
925 joined.push_str(&closer);
926 }
927 }
928 joined
929}
930
931pub(crate) fn parse_relationships_with_warnings(
955 text: &str,
956 mem: &str,
957 entity_id: Option<&EntityId>,
958) -> (Vec<Relationship>, Vec<crate::ops::WarningHint>) {
959 static RE: OnceLock<Regex> = OnceLock::new();
973 let re = RE.get_or_init(|| {
974 Regex::new(r"(?m)^\s*-\s*\*\*(\w+)\*\*:\s*\[\[([^\]\n]+)\]\](?P<tail>[^\n]*)").unwrap()
975 });
976 let mut relationships = Vec::new();
977 let mut warnings = Vec::new();
978 let masked = mask_code_blocks_and_spans(text);
986 for cap in re.captures_iter(&masked) {
987 let rel_type = text[cap.get(1).unwrap().range()].to_uppercase();
988 let target = wiki_link_to_id_lenient(&text[cap.get(2).unwrap().range()], mem);
994 if target.path().is_empty() {
1003 continue;
1004 }
1005 let tail = cap.name("tail").map(|m| &text[m.range()]).unwrap_or("");
1006 let description = match classify_description_tail(tail) {
1007 DescriptionTail::None => None,
1008 DescriptionTail::EmDash(text) => Some(text),
1009 DescriptionTail::Ambiguous(literal) => {
1010 if let Some(id) = entity_id {
1011 warnings.push(crate::ops::WarningHint::AmbiguousDescriptionDelimiter {
1012 from: id.clone(),
1013 rel_type: rel_type.clone(),
1014 target: target.clone(),
1015 trailing: literal,
1016 });
1017 }
1018 None
1019 }
1020 };
1021 relationships.push(Relationship {
1022 rel_type,
1023 target,
1024 description,
1025 });
1026 }
1027 (relationships, warnings)
1028}
1029
1030enum DescriptionTail {
1033 None,
1035 EmDash(String),
1038 Ambiguous(String),
1042}
1043
1044fn classify_description_tail(tail: &str) -> DescriptionTail {
1050 let trimmed_end = tail.trim_end();
1051 if trimmed_end.is_empty() {
1052 return DescriptionTail::None;
1053 }
1054 if let Some(rest) = trimmed_end.strip_prefix(" \u{2014} ") {
1056 if rest.is_empty() {
1057 return DescriptionTail::None;
1058 }
1059 return DescriptionTail::EmDash(rest.to_string());
1060 }
1061 if let Some(rest) = trimmed_end.strip_prefix(" \u{2014}") {
1065 return DescriptionTail::Ambiguous(format!(" \u{2014}{rest}"));
1067 }
1068 let starters = [" --", " -", " \u{2013}", " \u{2212}"];
1070 if starters
1071 .iter()
1072 .any(|prefix| trimmed_end.starts_with(prefix))
1073 {
1074 return DescriptionTail::Ambiguous(trimmed_end.to_string());
1075 }
1076 DescriptionTail::Ambiguous(trimmed_end.to_string())
1080}
1081
1082fn wiki_link_re() -> &'static Regex {
1094 static RE: OnceLock<Regex> = OnceLock::new();
1095 RE.get_or_init(|| Regex::new(r"\[\[([^\]]*)\]\]").unwrap())
1096}
1097
1098pub(crate) fn extract_inline_links(
1112 text: &str,
1113 mem: &str,
1114) -> Result<Vec<EntityId>, Vec<WikiLinkError>> {
1115 let stripped = mask_code_blocks_and_spans(text);
1116
1117 let link_re = wiki_link_re();
1118 let mut seen = HashSet::new();
1119 let mut links = Vec::new();
1120 let mut errors = Vec::new();
1121
1122 for cap in link_re.captures_iter(&stripped) {
1123 match wiki_link_to_id(&cap[1], mem) {
1124 Ok(id) => {
1125 if errors.is_empty() && seen.insert(id.0.clone()) {
1126 links.push(id);
1127 }
1128 }
1129 Err(e) => errors.push(e),
1130 }
1131 }
1132
1133 if errors.is_empty() {
1134 Ok(links)
1135 } else {
1136 Err(errors)
1137 }
1138}
1139
1140pub fn extract_inline_links_lenient(text: &str, mem: &str) -> Vec<EntityId> {
1147 let stripped = mask_code_blocks_and_spans(text);
1148
1149 let link_re = wiki_link_re();
1150 let mut seen = HashSet::new();
1151 let mut links = Vec::new();
1152
1153 for cap in link_re.captures_iter(&stripped) {
1154 if cap[1].is_empty() {
1159 continue;
1160 }
1161 let id = wiki_link_to_id_lenient(&cap[1], mem);
1162 if seen.insert(id.0.clone()) {
1163 links.push(id);
1164 }
1165 }
1166
1167 links
1168}
1169
1170pub fn compute_hash(content: &str) -> String {
1176 let mut hasher = Sha256::new();
1177 hasher.update(content.as_bytes());
1178 let result = hasher.finalize();
1179 crate::hex_lower(&result)[..16].to_string()
1180}
1181
1182#[derive(Debug, thiserror::Error)]
1187pub enum ParseError {
1188 #[error("missing frontmatter")]
1189 MissingFrontmatter,
1190 #[error("invalid frontmatter: {0}")]
1191 InvalidFrontmatter(String),
1192 #[error("missing title")]
1193 MissingTitle,
1194 #[error("io error: {0}")]
1195 Io(#[from] std::io::Error),
1196}
1197
1198#[cfg(test)]
1199mod tests {
1200 use super::*;
1201 use memstead_schema::{builtin_names, type_by_name};
1202 use std::sync::Arc;
1203
1204 fn spec_schema() -> Arc<TypeDefinition> {
1205 type_by_name(builtin_names::SPEC).unwrap()
1206 }
1207
1208 fn memo_schema() -> Arc<TypeDefinition> {
1209 type_by_name(builtin_names::MEMO).unwrap()
1210 }
1211
1212 #[test]
1213 fn parse_metadata_types() {
1214 let meta = parse_metadata("key: value\nnum: 42\nfloat: 0.85\nbool: true\nfalsy: false");
1215 assert_eq!(meta["key"], MetadataValue::String("value".to_string()));
1216 assert_eq!(meta["num"], MetadataValue::Integer(42));
1217 assert_eq!(meta["float"], MetadataValue::Float(0.85));
1218 assert_eq!(meta["bool"], MetadataValue::Bool(true));
1219 assert_eq!(meta["falsy"], MetadataValue::Bool(false));
1220 }
1221
1222 #[test]
1223 fn parse_metadata_strips_comments() {
1224 let meta = parse_metadata("key: value # this is a comment");
1225 assert_eq!(meta["key"], MetadataValue::String("value".to_string()));
1226 }
1227
1228 #[test]
1229 fn parse_metadata_strips_quotes() {
1230 let meta = parse_metadata("key: \"quoted value\"\nkey2: 'single'");
1231 assert_eq!(
1232 meta["key"],
1233 MetadataValue::String("quoted value".to_string())
1234 );
1235 assert_eq!(meta["key2"], MetadataValue::String("single".to_string()));
1236 }
1237
1238 #[test]
1239 fn parse_metadata_survives_malformed_values() {
1240 let meta = parse_metadata(
1243 "key: \"\nkey2: '\nkey3: \"\"\nkey4: ''\nkey5: \"unterminated\nkey6: mixed'\"",
1244 );
1245 assert_eq!(meta["key"], MetadataValue::String("\"".to_string()));
1246 assert_eq!(meta["key2"], MetadataValue::String("'".to_string()));
1247 assert_eq!(meta["key3"], MetadataValue::String(String::new()));
1248 assert_eq!(meta["key4"], MetadataValue::String(String::new()));
1249 assert_eq!(
1250 meta["key5"],
1251 MetadataValue::String("\"unterminated".to_string())
1252 );
1253 assert_eq!(meta["key6"], MetadataValue::String("mixed'\"".to_string()));
1254
1255 let meta =
1258 parse_metadata(":\n: value\nkey7: ✓\"\nkey8: 99999999999999999999999999\nkey9: -");
1259 assert_eq!(meta["key7"], MetadataValue::String("✓\"".to_string()));
1260 assert_eq!(
1261 meta["key8"],
1262 MetadataValue::String("99999999999999999999999999".to_string())
1263 );
1264 assert_eq!(meta["key9"], MetadataValue::String("-".to_string()));
1265 }
1266
1267 #[test]
1268 fn parse_metadata_skips_comments_and_empty() {
1269 let meta = parse_metadata("# comment\n\nkey: val\n---");
1270 assert_eq!(meta.len(), 1);
1271 assert_eq!(meta["key"], MetadataValue::String("val".to_string()));
1272 }
1273
1274 #[test]
1275 fn peek_type_finds_value() {
1276 let content = "---\ntype: memo\ntitle: Test\n---\n# Body\n";
1277 assert_eq!(
1278 peek_type_from_frontmatter(content),
1279 Some("memo".to_string())
1280 );
1281 }
1282
1283 #[test]
1284 fn peek_type_returns_none_when_missing() {
1285 let content = "---\ntitle: Test\n---\n# Body\n";
1286 assert_eq!(peek_type_from_frontmatter(content), None);
1287 }
1288
1289 #[test]
1290 fn peek_type_returns_none_without_frontmatter() {
1291 let content = "# Just a heading\n\nBody with type: concept inside text.\n";
1292 assert_eq!(peek_type_from_frontmatter(content), None);
1293 }
1294
1295 #[test]
1300 fn split_core_crlf_document_borrows_meta_and_body() {
1301 let content = "---\r\ntype: spec\r\nlevel: M0\r\n---\r\n# Title\r\n\r\nBody.\r\n";
1302 let (stripped, split) = split_frontmatter_core(content);
1303 assert_eq!(stripped, content);
1304 assert_eq!(
1305 split,
1306 Frontmatter::Present {
1307 meta: "type: spec\r\nlevel: M0\r",
1308 body: "# Title\r\n\r\nBody.\r\n"
1309 }
1310 );
1311 let (meta, body) = frontmatter_parts(content).unwrap();
1312 assert_eq!(meta, "type: spec\r\nlevel: M0\r");
1313 assert_eq!(body, "# Title\r\n\r\nBody.\r\n");
1314 assert_eq!(body_after_frontmatter(content), body);
1315 let marked = format!("\u{feff}{content}");
1317 assert_eq!(frontmatter_parts(&marked), Some((meta, body)));
1318 }
1319
1320 #[test]
1325 fn first_fence_not_at_document_start_is_no_frontmatter() {
1326 let content = "# Intro\n\n---\ntype: spec\n---\n\nBody.\n";
1327 assert_eq!(
1328 split_frontmatter_core(content),
1329 (content, Frontmatter::NoOpeningDelimiter)
1330 );
1331 assert_eq!(frontmatter_parts(content), None);
1332 assert_eq!(body_after_frontmatter(content), content);
1333 assert_eq!(peek_type_from_frontmatter(content), None);
1334 let unclosed = "---\ntype: spec\nno close\n";
1336 assert_eq!(
1337 split_frontmatter_core(unclosed),
1338 (unclosed, Frontmatter::Unclosed)
1339 );
1340 assert_eq!(frontmatter_parts(unclosed), None);
1341 }
1342
1343 #[test]
1344 fn peek_type_handles_windows_line_endings() {
1345 let content = "---\r\ntype: principle\r\n---\r\n# Body\r\n";
1346 assert_eq!(
1347 peek_type_from_frontmatter(content),
1348 Some("principle".to_string())
1349 );
1350 }
1351
1352 #[test]
1353 fn peek_type_strips_quotes_and_comments() {
1354 let quoted = "---\ntype: \"concept\"\n---\n";
1355 assert_eq!(
1356 peek_type_from_frontmatter(quoted),
1357 Some("concept".to_string())
1358 );
1359 let commented = "---\ntype: memo # kind of\n---\n";
1360 assert_eq!(
1361 peek_type_from_frontmatter(commented),
1362 Some("memo".to_string())
1363 );
1364 }
1365
1366 #[test]
1367 fn peek_type_empty_value_returns_none() {
1368 let content = "---\ntype:\n---\n";
1369 assert_eq!(peek_type_from_frontmatter(content), None);
1370 }
1371
1372 #[test]
1373 fn peek_type_ignores_legacy_schema_key() {
1374 let content = concat!("---\n", "schema", ": memo\n---\n");
1377 assert_eq!(peek_type_from_frontmatter(content), None);
1378 }
1379
1380 #[test]
1381 fn mask_code_blocks_basic() {
1382 let input = "before\n```\ncode [[link]]\n```\nafter";
1383 let masked = mask_code_blocks(input);
1384 assert!(!masked.contains("[[link]]"));
1385 assert!(masked.contains("before"));
1386 assert!(masked.contains("after"));
1387 }
1388
1389 #[test]
1390 fn mask_code_blocks_preserves_line_count() {
1391 let input = "line1\n```\ncode\nmore code\n```\nline6";
1392 let masked = mask_code_blocks(input);
1393 assert_eq!(input.lines().count(), masked.lines().count());
1394 }
1395
1396 #[test]
1397 fn mask_code_blocks_unclosed() {
1398 let input = "before\n```\ncode\nmore code";
1399 let masked = mask_code_blocks(input);
1400 assert!(masked.contains("before"));
1401 assert!(!masked.contains("code"));
1402 }
1403
1404 #[test]
1405 fn parse_relationships_basic() {
1406 let text = "- **USES**: [[target-entity]]\n- **PART_OF**: [[parent]]";
1407 let rels = parse_relationships_with_warnings(text, "specs", None).0;
1408 assert_eq!(rels.len(), 2);
1409 assert_eq!(rels[0].rel_type, "USES");
1410 assert_eq!(rels[0].target.0, "specs--target-entity");
1411 assert_eq!(rels[1].rel_type, "PART_OF");
1412 assert_eq!(rels[1].target.0, "specs--parent");
1413 assert!(rels[0].description.is_none());
1415 assert!(rels[1].description.is_none());
1416 }
1417
1418 #[test]
1419 fn parse_relationships_canonical_em_dash_captures_description() {
1420 let text = "- **OTHER**: [[a]] \u{2014} replaced by checkout-flow";
1421 let (rels, warnings) = parse_relationships_with_warnings(text, "specs", None);
1422 assert_eq!(rels.len(), 1);
1423 assert_eq!(
1424 rels[0].description.as_deref(),
1425 Some("replaced by checkout-flow")
1426 );
1427 assert!(warnings.is_empty(), "canonical em-dash does not warn");
1428 }
1429
1430 #[test]
1431 fn parse_relationships_em_dash_inside_description_body() {
1432 let text = "- **OTHER**: [[a]] \u{2014} note with — inside body";
1433 let (rels, warnings) = parse_relationships_with_warnings(text, "specs", None);
1434 assert_eq!(rels.len(), 1);
1435 assert_eq!(
1436 rels[0].description.as_deref(),
1437 Some("note with — inside body"),
1438 "the parser captures up to end-of-line; em-dashes inside the body survive"
1439 );
1440 assert!(warnings.is_empty());
1441 }
1442
1443 #[test]
1444 fn parse_relationships_ambiguous_double_hyphen_warns_and_drops_content() {
1445 let text = "- **USES**: [[a]] -- legacy delimiter";
1446 let entity_id = EntityId::new("specs", "src");
1447 let (rels, warnings) = parse_relationships_with_warnings(text, "specs", Some(&entity_id));
1448 assert_eq!(rels.len(), 1);
1449 assert!(rels[0].description.is_none(), "trailing content is dropped");
1450 assert_eq!(warnings.len(), 1);
1451 assert!(matches!(
1452 warnings[0],
1453 crate::ops::WarningHint::AmbiguousDescriptionDelimiter { .. }
1454 ));
1455 }
1456
1457 #[test]
1458 fn parse_relationships_ambiguous_single_hyphen_warns_and_drops_content() {
1459 let text = "- **USES**: [[a]] - single hyphen";
1460 let entity_id = EntityId::new("specs", "src");
1461 let (rels, warnings) = parse_relationships_with_warnings(text, "specs", Some(&entity_id));
1462 assert_eq!(rels.len(), 1);
1463 assert!(rels[0].description.is_none());
1464 assert_eq!(warnings.len(), 1);
1465 assert_eq!(warnings[0].code(), "AMBIGUOUS_DESCRIPTION_DELIMITER");
1466 }
1467
1468 #[test]
1469 fn parse_relationships_hyphenated_slug_target_parses_unambiguously() {
1470 let text = "- **USES**: [[some-slug-with-hyphens]] \u{2014} ok";
1471 let (rels, warnings) = parse_relationships_with_warnings(text, "specs", None);
1472 assert_eq!(rels.len(), 1);
1473 assert_eq!(rels[0].target.path(), "some-slug-with-hyphens");
1474 assert_eq!(rels[0].description.as_deref(), Some("ok"));
1475 assert!(warnings.is_empty());
1476 }
1477
1478 #[test]
1479 fn parse_full_entity() {
1480 let md = "\
1481---
1482type: spec
1483created_date: 2026-01-15
1484last_modified: 2026-04-12
1485level: M0
1486tags: backend, api
1487---
1488# Test Entity
1489
1490## Identity
1491
1492This is a test entity.
1493
1494## Purpose
1495
1496Testing the parser.
1497
1498## Relationships
1499
1500- **USES**: [[other-entity]]
1501
1502## Specifies
1503
1504Some specification content with [[inline-link]].
1505";
1506 let result = parse_markdown(md, "test-entity.md", &spec_schema(), "specs").unwrap();
1507 let entity = &result.entity;
1508 assert_eq!(entity.id.0, "specs--test-entity");
1509 assert_eq!(entity.title, "Test Entity");
1510 assert_eq!(entity.mem, "specs");
1511 assert_eq!(
1512 entity.metadata["type"],
1513 MetadataValue::String("spec".to_string())
1514 );
1515 assert_eq!(
1516 entity.metadata["level"],
1517 MetadataValue::String("M0".to_string())
1518 );
1519 assert_eq!(
1520 entity.metadata["tags"],
1521 MetadataValue::String("backend, api".to_string())
1522 );
1523 assert_eq!(entity.sections["identity"], "This is a test entity.");
1524 assert_eq!(entity.sections["purpose"], "Testing the parser.");
1525 assert_eq!(entity.relationships.len(), 1);
1526 assert_eq!(entity.relationships[0].rel_type, "USES");
1527 assert_eq!(entity.relationships[0].target.0, "specs--other-entity");
1528 assert_eq!(result.inline_links.len(), 1);
1529 assert_eq!(result.inline_links[0].0, "specs--inline-link");
1530 }
1531
1532 #[test]
1533 fn parse_full_entity_memo_schema() {
1534 let md = "\
1535---
1536type: memo
1537created_date: 2026-01-15
1538last_modified: 2026-04-12
1539status: active
1540tags: decision, architecture
1541---
1542# Use Sled For Storage
1543
1544## Claim
1545
1546Sled is the right embedded store for this workload.
1547
1548## Context
1549
1550We evaluated sled, rocksdb, and sqlite for the in-process graph cache.
1551
1552## Substance
1553
1554Sled wins on pure-Rust dependency footprint.
1555";
1556 let result = parse_markdown(md, "use-sled.md", &memo_schema(), "memos").unwrap();
1557 let entity = &result.entity;
1558 assert_eq!(entity.id.0, "memos--use-sled");
1559 assert_eq!(entity.title, "Use Sled For Storage");
1560 assert_eq!(entity.mem, "memos");
1561 assert_eq!(
1562 entity.metadata["type"],
1563 MetadataValue::String("memo".to_string())
1564 );
1565 assert_eq!(
1566 entity.metadata["status"],
1567 MetadataValue::String("active".to_string())
1568 );
1569 assert_eq!(
1570 entity.sections["claim"],
1571 "Sled is the right embedded store for this workload."
1572 );
1573 assert_eq!(
1574 entity.sections["context"],
1575 "We evaluated sled, rocksdb, and sqlite for the in-process graph cache."
1576 );
1577 assert_eq!(
1578 entity.sections["substance"],
1579 "Sled wins on pure-Rust dependency footprint."
1580 );
1581 assert!(!entity.sections.contains_key("identity"));
1582 assert!(!entity.sections.contains_key("purpose"));
1583 }
1584
1585 #[test]
1586 fn parse_entity_without_frontmatter() {
1587 let md = "# No Frontmatter\n\n## Identity\n\nJust a title and section.";
1588 let result = parse_markdown(md, "no-fm.md", &spec_schema(), "specs").unwrap();
1589 assert_eq!(result.entity.title, "No Frontmatter");
1590 assert_eq!(result.entity.metadata.len(), 1);
1592 assert_eq!(
1593 result.entity.metadata.get("type"),
1594 Some(&MetadataValue::String("spec".to_string()))
1595 );
1596 }
1597
1598 #[test]
1599 fn parse_entity_code_blocks_not_detected() {
1600 let md = "\
1601---
1602type: spec
1603---
1604# Code Test
1605
1606## Identity
1607
1608Test entity.
1609
1610## Specifies
1611
1612```
1613## Not A Section
1614- **USES**: [[not-a-link]]
1615```
1616
1617Real content after code block.
1618";
1619 let result = parse_markdown(md, "code-test.md", &spec_schema(), "specs").unwrap();
1620 assert!(!result.entity.sections.contains_key("not a section"));
1622 assert!(result.inline_links.is_empty());
1624 }
1625
1626 #[test]
1633 fn bom_prefixed_frontmatter_is_recognized() {
1634 let md = "\u{feff}---\ntype: spec\n---\n# Bom Entity\n\n## Identity\n\nBody.\n";
1635 assert_eq!(peek_type_from_frontmatter(md), Some("spec".to_string()));
1636 assert_eq!(
1637 body_after_frontmatter(md),
1638 "# Bom Entity\n\n## Identity\n\nBody.\n"
1639 );
1640 let (meta, body) = split_frontmatter(md).unwrap();
1641 assert_eq!(meta, "type: spec");
1642 assert_eq!(body, "# Bom Entity\n\n## Identity\n\nBody.\n");
1643 let result = parse_markdown(md, "bom.md", &spec_schema(), "specs").unwrap();
1644 assert_eq!(
1645 result.entity.metadata["type"],
1646 MetadataValue::String("spec".to_string())
1647 );
1648 assert_eq!(result.entity.sections["identity"], "Body.");
1649 }
1650
1651 #[test]
1658 fn open_fence_in_section_content_does_not_swallow_following_sections() {
1659 let md = "\
1660---
1661type: spec
1662---
1663# Code Test
1664
1665## Identity
1666
1667Base.
1668
1669## Specifies
1670
1671```
1672truncated code with no closer";
1673 let schema = spec_schema();
1674 let e1 = parse_markdown(md, "open-fence.md", &schema, "specs").unwrap();
1675 let m1 = crate::entity::generator::generate_markdown(&e1.entity, &schema);
1676 let e2 = parse_markdown(&m1, "open-fence.md", &schema, "specs").unwrap();
1677 assert_eq!(
1678 e2.entity.sections["identity"], "Base.",
1679 "sections before the open fence survive"
1680 );
1681 assert!(
1682 !e2.entity.sections["specifies"].contains("## Constraints"),
1683 "the generated sections after the fence are not absorbed into it"
1684 );
1685 let m2 = crate::entity::generator::generate_markdown(&e2.entity, &schema);
1686 assert_eq!(
1687 m1, m2,
1688 "parse→generate is a fixpoint after one normalising round"
1689 );
1690 }
1691
1692 #[test]
1700 fn catch_all_reconstruction_is_document_ordered_and_idempotent() {
1701 let md = "\
1702---
1703type: spec
1704---
1705# Multi Unknown
1706
1707## Identity
1708
1709Base.
1710
1711## Claim
1712
1713First unknown.
1714
1715## Context
1716
1717Second unknown.
1718
1719## Substance
1720
1721Third unknown.
1722";
1723 let schema = spec_schema();
1724 let e1 = parse_markdown(md, "multi-unknown.md", &schema, "specs").unwrap();
1725 assert_eq!(
1726 e1.entity.sections["specifies"],
1727 "## Claim\nFirst unknown.\n\n## Context\nSecond unknown.\n\n## Substance\nThird unknown.",
1728 "non-schema sections land in the catch-all in document order"
1729 );
1730 let m1 = crate::entity::generator::generate_markdown(&e1.entity, &schema);
1731 let e2 = parse_markdown(&m1, "multi-unknown.md", &schema, "specs").unwrap();
1732 let m2 = crate::entity::generator::generate_markdown(&e2.entity, &schema);
1733 assert_eq!(
1734 m1, m2,
1735 "parse→generate is idempotent over multi-unknown-section input"
1736 );
1737 }
1738
1739 #[test]
1748 fn first_line_whitespace_prefix_survives_storage_and_round_trips() {
1749 let schema = spec_schema();
1750 let md = "---\ntype: spec\n---\n# T\n\n## Identity\n\u{b}```\nx\n\n## Purpose\np\n";
1751 let e1 = parse_markdown(md, "vt.md", &schema, "specs").unwrap();
1752 assert_eq!(
1753 e1.entity.sections["identity"], "\u{b}```\nx",
1754 "the first visible line keeps its whitespace prefix byte-exactly"
1755 );
1756 let m1 = crate::entity::generator::generate_markdown(&e1.entity, &schema);
1757 let e2 = parse_markdown(&m1, "vt.md", &schema, "specs").unwrap();
1758 let m2 = crate::entity::generator::generate_markdown(&e2.entity, &schema);
1759 assert_eq!(m1, m2, "parse→generate is a fixpoint");
1760 }
1761
1762 #[test]
1773 fn merged_open_html_block_is_closed_so_later_fences_keep_masking() {
1774 let schema = spec_schema();
1775 let md = "\
1776---
1777type: spec
1778---
1779# T
1780
1781## Claim
1782<!X
1783
1784## Specifies
1785done >
1786
1787## Later
1788~~~
1789## Hidden
1790";
1791 let e1 = parse_markdown(md, "html.md", &schema, "specs").unwrap();
1792 assert_eq!(
1793 e1.entity.sections["specifies"],
1794 "done >\n\n## Claim\n<!X\n>\n\n## Later\n~~~\n## Hidden\n~~~",
1795 "the open HTML block closes before the next piece, the dangling fence after it"
1796 );
1797 let m1 = crate::entity::generator::generate_markdown(&e1.entity, &schema);
1798 let e2 = parse_markdown(&m1, "html.md", &schema, "specs").unwrap();
1799 let m2 = crate::entity::generator::generate_markdown(&e2.entity, &schema);
1800 assert_eq!(m1, m2, "parse→generate is a fixpoint");
1801 }
1802
1803 #[test]
1817 fn section_that_stood_inside_the_previous_sections_block_is_read_as_written() {
1818 let schema = spec_schema();
1819 let md = "\
1820---
1821type: spec
1822---
1823# T
1824
1825## First
1826<!X
1827
1828## Second
1829<!--
1830>
1831~~~
1832## Hidden
1833";
1834 let e1 = parse_markdown(md, "html.md", &schema, "specs").unwrap();
1835 assert_eq!(
1836 e1.entity.sections["specifies"], "## First\n<!X\n>\n\n## Second\n<!--\n>\n~~~\n-->",
1837 "the second section ends where a neutral read would split it, and its comment closes there"
1838 );
1839 assert_eq!(
1840 e1.entity.raw_section_headings,
1841 vec!["First", "Second", "Hidden"],
1842 "the surfaced line is a boundary on the first parse"
1843 );
1844 let m1 = crate::entity::generator::generate_markdown(&e1.entity, &schema);
1845 let e2 = parse_markdown(&m1, "html.md", &schema, "specs").unwrap();
1846 let m2 = crate::entity::generator::generate_markdown(&e2.entity, &schema);
1847 assert_eq!(m1, m2, "parse→generate is a fixpoint");
1848 }
1849
1850 #[test]
1859 fn section_that_stood_inside_a_preamble_block_is_read_as_written() {
1860 let schema = spec_schema();
1861 let md = "\
1862---
1863type: spec
1864---
1865# T
1866<!X
1867## Only
1868<!--
1869>
1870~~~
1871## Hidden
1872";
1873 let e1 = parse_markdown(md, "html.md", &schema, "specs").unwrap();
1874 assert_eq!(
1875 e1.entity.sections["specifies"], "## Only\n<!--\n>\n~~~\n-->",
1876 "the section ends where a neutral read would split it, and its comment closes there"
1877 );
1878 let m1 = crate::entity::generator::generate_markdown(&e1.entity, &schema);
1879 let e2 = parse_markdown(&m1, "html.md", &schema, "specs").unwrap();
1880 let m2 = crate::entity::generator::generate_markdown(&e2.entity, &schema);
1881 assert_eq!(m1, m2, "parse→generate is a fixpoint");
1882 }
1883
1884 #[test]
1894 fn indented_heading_lookalike_stays_content_and_round_trips() {
1895 let md = "\
1896---
1897type: spec
1898---
1899# Promoted Heading
1900
1901## Identity
1902
1903Base.
1904
1905## Unknown Extra
1906
1907 ## Specifies
1908
1909Some content that must survive.
1910";
1911 let schema = spec_schema();
1912 let e1 = parse_markdown(md, "indent.md", &schema, "specs").unwrap();
1913 assert!(
1914 e1.entity.sections["specifies"].contains(" ## Specifies"),
1915 "the indented lookalike keeps its indentation inside the catch-all"
1916 );
1917 assert!(
1918 e1.entity.sections["specifies"].contains("Some content that must survive."),
1919 "content after the lookalike is preserved"
1920 );
1921 let m1 = crate::entity::generator::generate_markdown(&e1.entity, &schema);
1922 let e2 = parse_markdown(&m1, "indent.md", &schema, "specs").unwrap();
1923 let m2 = crate::entity::generator::generate_markdown(&e2.entity, &schema);
1924 assert_eq!(
1925 m1, m2,
1926 "parse→generate is a fixpoint after one normalising round"
1927 );
1928 assert!(
1929 e2.entity.sections["specifies"].contains("Some content that must survive."),
1930 "no content is lost across rounds"
1931 );
1932 }
1933
1934 #[test]
1935 fn compute_hash_deterministic() {
1936 let hash1 = compute_hash("test content");
1937 let hash2 = compute_hash("test content");
1938 assert_eq!(hash1, hash2);
1939 assert_eq!(hash1.len(), 16);
1940 }
1941
1942 #[test]
1943 fn compute_hash_differs() {
1944 let hash1 = compute_hash("content a");
1945 let hash2 = compute_hash("content b");
1946 assert_ne!(hash1, hash2);
1947 }
1948
1949 #[test]
1950 fn is_float_literal_matches() {
1951 assert!(is_float_literal("0.85"));
1952 assert!(is_float_literal("-1.5"));
1953 assert!(is_float_literal("100.0"));
1954 assert!(!is_float_literal(".5"));
1955 assert!(!is_float_literal("1."));
1956 assert!(!is_float_literal("42"));
1957 assert!(!is_float_literal("hello"));
1958 }
1959
1960 #[test]
1961 fn is_integer_literal_matches() {
1962 assert!(is_integer_literal("42"));
1963 assert!(is_integer_literal("-1"));
1964 assert!(is_integer_literal("0"));
1965 assert!(!is_integer_literal("0.5"));
1966 assert!(!is_integer_literal("hello"));
1967 assert!(!is_integer_literal(""));
1968 }
1969
1970 #[test]
1976 fn parse_preserves_frontmatter_key_order() {
1977 let md = "\
1978---
1979type: principle
1980universality: domain-wide
1981authority: proposed
1982tags: a, b, c
1983created_date: 2026-01-15
1984last_modified: 2026-04-12
1985---
1986# Key Order
1987";
1988 let result = parse_markdown(
1989 md,
1990 "key-order.md",
1991 &type_by_name(builtin_names::PRINCIPLE).unwrap(),
1992 "knowledge",
1993 )
1994 .unwrap();
1995 let keys: Vec<&str> = result.entity.metadata.keys().map(|s| s.as_str()).collect();
1996 assert_eq!(
1997 keys,
1998 vec![
1999 "type",
2000 "universality",
2001 "authority",
2002 "tags",
2003 "created_date",
2004 "last_modified",
2005 ],
2006 "metadata iteration must preserve frontmatter declaration order"
2007 );
2008 }
2009
2010 #[test]
2018 fn parse_write_roundtrip_preserves_section_order() {
2019 let md = "\
2020---
2021type: spec
2022created_date: 2026-01-15
2023last_modified: 2026-04-12
2024level: M0
2025---
2026# Order Roundtrip
2027
2028## Identity
2029
2030Identity content.
2031
2032## Purpose
2033
2034Purpose content.
2035
2036## Specifies
2037
2038Specifies content.
2039";
2040 let schema = spec_schema();
2041 let first = parse_markdown(md, "order-roundtrip.md", &schema, "specs").unwrap();
2042 let regenerated = crate::entity::generator::generate_markdown(&first.entity, &schema);
2043 let second = parse_markdown(®enerated, "order-roundtrip.md", &schema, "specs").unwrap();
2044
2045 let first_keys: Vec<&String> = first.entity.sections.keys().collect();
2046 let second_keys: Vec<&String> = second.entity.sections.keys().collect();
2047 assert_eq!(
2048 first_keys, second_keys,
2049 "section iteration order must survive parse -> generate -> parse"
2050 );
2051 }
2052
2053 #[test]
2063 fn parser_extracts_single_h3() {
2064 let md = "\
2065---
2066type: spec
2067---
2068# Entity
2069
2070## Identity
2071
2072Body.
2073
2074## Specifies
2075
2076### Response Shapes
2077
2078Content under response shapes.
2079";
2080 let result = parse_markdown(md, "h3-single.md", &spec_schema(), "specs").unwrap();
2081 let spans = result
2082 .entity
2083 .heading_spans
2084 .get("specifies")
2085 .expect("specifies section should have spans");
2086 assert_eq!(spans.len(), 1);
2087 assert_eq!(spans[0].level, 3);
2088 assert_eq!(spans[0].title, "Response Shapes");
2089 assert_eq!(spans[0].start_offset, 0);
2091 let section = result.entity.sections.get("specifies").unwrap();
2092 assert_eq!(spans[0].end_offset, section.len());
2093 assert!(
2095 result
2096 .entity
2097 .heading_spans
2098 .get("identity")
2099 .is_none_or(Vec::is_empty)
2100 );
2101 }
2102
2103 #[test]
2104 fn parser_extracts_nested_h3_h4() {
2105 let md = "\
2106---
2107type: spec
2108---
2109# Entity
2110
2111## Identity
2112
2113Body.
2114
2115## Specifies
2116
2117### Outer
2118
2119Outer body.
2120
2121#### Inner
2122
2123Inner body.
2124";
2125 let result = parse_markdown(md, "h3-h4.md", &spec_schema(), "specs").unwrap();
2126 let spans = result.entity.heading_spans.get("specifies").unwrap();
2127 assert_eq!(spans.len(), 2, "both H3 and H4 must be recorded");
2128 assert_eq!(spans[0].level, 3);
2129 assert_eq!(spans[0].title, "Outer");
2130 assert_eq!(spans[1].level, 4);
2131 assert_eq!(spans[1].title, "Inner");
2132 assert!(
2133 spans[0].start_offset < spans[1].start_offset,
2134 "spans must be in document order"
2135 );
2136 assert!(
2138 spans[0].end_offset > spans[1].start_offset,
2139 "outer H3 must contain inner H4 by offset"
2140 );
2141 }
2142
2143 #[test]
2144 fn parser_ignores_headings_in_code_blocks() {
2145 let md = "\
2146---
2147type: spec
2148---
2149# Entity
2150
2151## Identity
2152
2153Body.
2154
2155## Specifies
2156
2157Prefix.
2158
2159```
2160### Not a heading
2161Still code.
2162```
2163
2164Suffix.
2165";
2166 let result = parse_markdown(md, "h3-code.md", &spec_schema(), "specs").unwrap();
2167 let spans = result
2168 .entity
2169 .heading_spans
2170 .get("specifies")
2171 .cloned()
2172 .unwrap_or_default();
2173 assert!(
2174 spans.is_empty(),
2175 "a '### ' inside a fenced block must not register as a heading span: {spans:?}"
2176 );
2177 }
2178
2179 #[test]
2180 fn parser_handles_level_skip() {
2181 let md = "\
2182---
2183type: spec
2184---
2185# Entity
2186
2187## Identity
2188
2189Body.
2190
2191## Specifies
2192
2193#### Skipped To H4
2194
2195Content under a sudden H4 — no virtual H3 is inserted.
2196";
2197 let result = parse_markdown(md, "h2-h4.md", &spec_schema(), "specs").unwrap();
2198 let spans = result.entity.heading_spans.get("specifies").unwrap();
2199 assert_eq!(spans.len(), 1);
2200 assert_eq!(spans[0].level, 4);
2201 assert_eq!(spans[0].title, "Skipped To H4");
2202 }
2203
2204 #[test]
2205 fn parser_handles_duplicate_siblings() {
2206 let md = "\
2207---
2208type: spec
2209---
2210# Entity
2211
2212## Identity
2213
2214Body.
2215
2216## Specifies
2217
2218### Same Title
2219
2220First occurrence body.
2221
2222### Same Title
2223
2224Second occurrence body.
2225";
2226 let result = parse_markdown(md, "h3-dup.md", &spec_schema(), "specs").unwrap();
2227 let spans = result.entity.heading_spans.get("specifies").unwrap();
2228 assert_eq!(spans.len(), 2, "duplicate siblings must produce two spans");
2229 assert_eq!(spans[0].title, spans[1].title);
2230 assert_ne!(
2231 spans[0].start_offset, spans[1].start_offset,
2232 "spans with identical titles must be distinguishable by offset"
2233 );
2234 assert!(
2236 spans[0].end_offset <= spans[1].start_offset,
2237 "first sibling must close before the second starts"
2238 );
2239 }
2240
2241 #[test]
2246 fn duplicate_declared_heading_two_populated_keeps_first_warns() {
2247 let md = "---\ntype: spec\n---\n# Title\n\n## Identity\n\nfirst body\n\n## Identity\n\nsecond body\n";
2248 let result = parse_markdown(md, "x.md", &spec_schema(), "v").unwrap();
2249 assert_eq!(
2250 result.entity.sections.get("identity").map(String::as_str),
2251 Some("first body"),
2252 "first body must win"
2253 );
2254 assert!(
2255 !result
2256 .entity
2257 .sections
2258 .get("identity")
2259 .unwrap()
2260 .contains("## Identity"),
2261 "storage value must not embed a duplicate heading"
2262 );
2263 assert_eq!(result.parse_warnings.len(), 1);
2264 match &result.parse_warnings[0] {
2265 crate::ops::WarningHint::DuplicateSectionHeading {
2266 section_key,
2267 heading,
2268 occurrences,
2269 ..
2270 } => {
2271 assert_eq!(section_key, "identity");
2272 assert_eq!(heading, "Identity");
2273 assert_eq!(*occurrences, 2);
2274 }
2275 other => panic!("expected DuplicateSectionHeading, got {other:?}"),
2276 }
2277 }
2278
2279 #[test]
2280 fn duplicate_declared_heading_blank_then_populated_keeps_blank() {
2281 let md =
2285 "---\ntype: spec\n---\n# Title\n\n## Identity\n\n## Identity\n\nleftover content\n";
2286 let result = parse_markdown(md, "x.md", &spec_schema(), "v").unwrap();
2287 assert_eq!(
2288 result.entity.sections.get("identity").map(String::as_str),
2289 Some(""),
2290 "first (blank) occurrence wins; second body is dropped"
2291 );
2292 assert_eq!(result.parse_warnings.len(), 1);
2293 }
2294
2295 #[test]
2296 fn duplicate_declared_heading_three_occurrences() {
2297 let md = "---\ntype: spec\n---\n# Title\n\n## Constraints\n\nA\n\n## Constraints\n\n## Constraints\n\nC\n";
2298 let result = parse_markdown(md, "x.md", &spec_schema(), "v").unwrap();
2299 assert_eq!(
2300 result
2301 .entity
2302 .sections
2303 .get("constraints")
2304 .map(String::as_str),
2305 Some("A"),
2306 );
2307 assert_eq!(result.parse_warnings.len(), 1);
2308 match &result.parse_warnings[0] {
2309 crate::ops::WarningHint::DuplicateSectionHeading { occurrences, .. } => {
2310 assert_eq!(*occurrences, 3);
2311 }
2312 _ => unreachable!(),
2313 }
2314 }
2315
2316 #[test]
2317 fn no_warning_when_each_declared_section_appears_once() {
2318 let md = "---\ntype: spec\n---\n# Title\n\n## Identity\n\nID\n\n## Purpose\n\nP\n\n## Constraints\n\nC\n";
2319 let result = parse_markdown(md, "x.md", &spec_schema(), "v").unwrap();
2320 assert!(result.parse_warnings.is_empty());
2321 }
2322
2323 #[test]
2324 fn no_warning_when_catch_all_section_repeats() {
2325 let md =
2328 "---\ntype: spec\n---\n# Title\n\n## Specifies\n\nfirst\n\n## Specifies\n\nsecond\n";
2329 let result = parse_markdown(md, "x.md", &spec_schema(), "v").unwrap();
2330 assert!(
2331 result.parse_warnings.is_empty(),
2332 "catch-all repetition must not warn"
2333 );
2334 }
2335
2336 #[test]
2343 fn duplicate_realization_does_not_concatenate_headers_in_storage() {
2344 let md = "---\ntype: spec\n---\n# Title\n\n## Identity\n\nID\n\n## Realization\n\n- a.mjs\n- b.mjs\n\n## Realization\n\n## Realization\n\n- c.mjs\n\n## Constraints\n\nC\n";
2345 let result = parse_markdown(md, "x.md", &spec_schema(), "v").unwrap();
2346 let catch_all = result.entity.sections.get("specifies").unwrap();
2347 let header_count = catch_all.matches("## Realization").count();
2348 assert!(
2349 header_count <= 1,
2350 "catch-all bucket must not contain multiple `## Realization` headers — got {header_count}: {catch_all:?}"
2351 );
2352 }
2353
2354 #[test]
2360 fn parse_render_round_trip_collapses_duplicate_headings() {
2361 let md = "---\ntype: spec\n---\n# Title\n\n## Identity\n\nA\n\n## Identity\n\n## Identity\n\nC\n\n## Purpose\n\nP\n";
2362 let result = parse_markdown(md, "x.md", &spec_schema(), "v").unwrap();
2363 let rendered = crate::render::render_entity_markdown(&result.entity, None);
2364 let identity_count = rendered.matches("## Identity").count();
2365 assert_eq!(
2366 identity_count, 1,
2367 "rendered output must carry exactly one `## Identity`, got {identity_count}: {rendered}"
2368 );
2369 assert!(rendered.contains("\n## Identity\n\nA\n"));
2371 assert!(!rendered.contains("C\n"), "second body must not survive");
2372 }
2373}
2374
2375#[cfg(test)]
2381mod commonmark_referee {
2382 use super::*;
2383 use memstead_schema::{builtin_names, type_by_name};
2384 use std::sync::Arc;
2385
2386 fn spec_schema() -> Arc<TypeDefinition> {
2387 type_by_name(builtin_names::SPEC).unwrap()
2388 }
2389
2390 fn entity_with_specifies(body: &str) -> ParseResult {
2392 let md = format!(
2393 "---\ntype: spec\n---\n\n# Referee Test\n\n## Identity\n\nx\n\n## Specifies\n\n{body}\n"
2394 );
2395 parse_markdown(&md, "referee-test.md", &spec_schema(), "specs").unwrap()
2396 }
2397
2398 fn headings(result: &ParseResult) -> Vec<&str> {
2399 result
2400 .entity
2401 .raw_section_headings
2402 .iter()
2403 .map(String::as_str)
2404 .collect()
2405 }
2406
2407 fn link_targets(result: &ParseResult) -> Vec<String> {
2408 result.inline_links.iter().map(|id| id.0.clone()).collect()
2409 }
2410
2411 #[test]
2414 fn complement_prose_headings_and_links_still_work() {
2415 let r = entity_with_specifies("See [[real-target]] here.");
2416 assert_eq!(headings(&r), vec!["Identity", "Specifies"]);
2417 assert_eq!(link_targets(&r), vec!["specs--real-target".to_string()]);
2418 assert_eq!(r.entity.title, "Referee Test");
2419 }
2420
2421 #[test]
2422 fn class_1_indented_code_block() {
2423 let r = entity_with_specifies("Example:\n\n ## Not A Section\n [[not-a-link]]\n");
2424 assert_eq!(headings(&r), vec!["Identity", "Specifies"]);
2425 assert!(link_targets(&r).is_empty(), "{:?}", link_targets(&r));
2426 }
2427
2428 #[test]
2429 fn class_2_fence_indented_one_to_three_spaces() {
2430 let r = entity_with_specifies(
2431 "- item\n\n ```\n ## Not A Section\n [[not-a-link]]\n ```\n",
2432 );
2433 assert_eq!(headings(&r), vec!["Identity", "Specifies"]);
2434 assert!(link_targets(&r).is_empty(), "{:?}", link_targets(&r));
2435 }
2436
2437 #[test]
2438 fn class_3_tilde_fence() {
2439 let r = entity_with_specifies("~~~\n## Not A Section\n[[not-a-link]]\n~~~\n");
2440 assert_eq!(headings(&r), vec!["Identity", "Specifies"]);
2441 assert!(link_targets(&r).is_empty(), "{:?}", link_targets(&r));
2442 }
2443
2444 #[test]
2445 fn class_4_info_string_on_the_closing_line() {
2446 let r = entity_with_specifies(
2447 "```\ncode\n``` still-code\n## Not A Section\n[[not-a-link]]\n```\n",
2448 );
2449 assert_eq!(headings(&r), vec!["Identity", "Specifies"]);
2450 assert!(link_targets(&r).is_empty(), "{:?}", link_targets(&r));
2451 }
2452
2453 #[test]
2454 fn class_5_fence_inside_a_blockquote() {
2455 let r = entity_with_specifies("> ```\n> ## Not A Section\n> [[not-a-link]]\n> ```\n");
2456 assert_eq!(headings(&r), vec!["Identity", "Specifies"]);
2457 assert!(link_targets(&r).is_empty(), "{:?}", link_targets(&r));
2458 }
2459
2460 #[test]
2461 fn class_6_opening_fence_length_is_honoured_on_close() {
2462 let r = entity_with_specifies("````\n```\n## Not A Section\n[[not-a-link]]\n```\n````\n");
2463 assert_eq!(headings(&r), vec!["Identity", "Specifies"]);
2464 assert!(link_targets(&r).is_empty(), "{:?}", link_targets(&r));
2465 }
2466
2467 #[test]
2469 fn a_heading_inside_a_code_block_never_becomes_the_title() {
2470 let md =
2471 "---\ntype: spec\n---\n\n```\n# Fake Title\n```\n\n# Real Title\n\n## Identity\n\nx\n";
2472 let r = parse_markdown(md, "title-test.md", &spec_schema(), "specs").unwrap();
2473 assert_eq!(r.entity.title, "Real Title");
2474 }
2475
2476 #[test]
2479 fn a_code_block_only_body_falls_back_to_the_filename() {
2480 let md = "---\ntype: spec\n---\n\n # Fake Title\n\n## Identity\n\nx\n";
2481 let r = parse_markdown(md, "fallback-test.md", &spec_schema(), "specs").unwrap();
2482 assert_eq!(r.entity.title, "fallback-test");
2483 }
2484
2485 #[test]
2486 fn heading_spans_ignore_code_block_content() {
2487 let r = entity_with_specifies("### Real Sub\n\n~~~\n### Fake Sub\n~~~\n");
2488 let spans = r.entity.heading_spans.get("specifies").expect("spans");
2489 let titles: Vec<&str> = spans.iter().map(|s| s.title.as_str()).collect();
2490 assert_eq!(titles, vec!["Real Sub"]);
2491 }
2492
2493 #[test]
2498 fn inline_code_spans_hide_links_on_the_extraction_path() {
2499 let r = entity_with_specifies("`[[hidden-one]]` and ``[[hidden-two]]`` but [[visible]].");
2500 assert_eq!(link_targets(&r), vec!["specs--visible".to_string()]);
2501 }
2502
2503 #[test]
2507 fn empty_wiki_link_target_is_refused_by_the_strict_extractor() {
2508 let errors = extract_inline_links("an empty [[]] link", "specs")
2509 .expect_err("empty target must refuse");
2510 assert_eq!(errors.len(), 1, "{errors:?}");
2511 }
2512
2513 #[test]
2516 fn empty_wiki_link_target_yields_no_id_on_the_lenient_path() {
2517 assert!(extract_inline_links_lenient("an empty [[]] link", "specs").is_empty());
2518 }
2519
2520 #[test]
2526 fn merge_conflict_markers_are_seen_through_fence_shaped_frontmatter() {
2527 let body = "\n# T\n\n## Identity\n\n<<<<<<< HEAD\nours\n=======\ntheirs\n>>>>>>> branch\n";
2528 for fm in [
2529 "---\ntype: spec\n---",
2530 "---\ntype: spec\nnotes: |\n ```rust\n fn x() {}\n---",
2531 "---\ntype: spec\nnotes: |\n ~~~\n---",
2532 "---\ntype: spec\nnotes: |\n indented block\n---",
2533 ] {
2534 assert!(
2535 has_merge_conflict_markers(&format!("{fm}{body}")),
2536 "conflict markers must be seen through frontmatter: {fm:?}"
2537 );
2538 }
2539 }
2540
2541 #[test]
2544 fn merge_conflict_markers_in_frontmatter_are_seen() {
2545 let content =
2546 "---\n<<<<<<< HEAD\ntype: spec\n=======\ntype: memo\n>>>>>>> branch\n---\n\n# T\n";
2547 assert!(has_merge_conflict_markers(content));
2548 }
2549
2550 #[test]
2553 fn a_fenced_conflict_marker_example_still_does_not_trip_the_guard() {
2554 let content = "---\ntype: spec\n---\n\n# T\n\n## Identity\n\n```\n<<<<<<< HEAD\nours\n=======\ntheirs\n>>>>>>> branch\n```\n";
2555 assert!(!has_merge_conflict_markers(content));
2556 }
2557
2558 #[test]
2564 fn a_relationship_row_inside_a_code_block_is_not_a_relationship() {
2565 for body in [
2566 "```\n- **REFERENCES**: [[ghost]]\n```",
2567 "~~~\n- **REFERENCES**: [[ghost]]\n~~~",
2568 " - **REFERENCES**: [[ghost]]",
2569 "> ```\n> - **REFERENCES**: [[ghost]]\n> ```",
2570 "````\n```\n- **REFERENCES**: [[ghost]]\n```\n````",
2571 ] {
2572 let (rels, _) = parse_relationships_with_warnings(body, "specs", None);
2573 assert!(
2574 rels.is_empty(),
2575 "code-block row must not become an edge: {body:?} -> {rels:?}"
2576 );
2577 }
2578 }
2579
2580 #[test]
2587 fn a_relationship_row_inside_an_inline_code_span_is_not_a_relationship() {
2588 for body in [
2589 "Example `open\n - **REFERENCES**: [[ghost]]\nclose`",
2595 "A `- **REFERENCES**: [[ghost]]` sample.",
2596 "A ``- **REFERENCES**: [[ghost]]`` sample.",
2597 ] {
2598 let (rels, _) = parse_relationships_with_warnings(body, "specs", None);
2599 assert!(
2600 rels.is_empty(),
2601 "code-span row must not become an edge: {body:?} -> {rels:?}"
2602 );
2603 }
2604 }
2605
2606 #[test]
2610 fn real_relationship_rows_are_unchanged_by_the_mask() {
2611 let body = "- **REFERENCES**: [[alpha]]\n- **uses**: [[beta]] — because it must\n\n```\n- **REFERENCES**: [[ghost]]\n```\n";
2612 let (rels, _) = parse_relationships_with_warnings(body, "specs", None);
2613 assert_eq!(rels.len(), 2, "{rels:?}");
2614 assert_eq!(rels[0].rel_type, "REFERENCES");
2615 assert_eq!(rels[0].target.0, "specs--alpha");
2616 assert_eq!(rels[0].description, None);
2617 assert_eq!(
2618 rels[1].rel_type, "USES",
2619 "case is normalised from the original"
2620 );
2621 assert_eq!(rels[1].target.0, "specs--beta");
2622 assert_eq!(rels[1].description.as_deref(), Some("because it must"));
2623 }
2624
2625 #[test]
2626 fn ambiguous_delimiter_warning_still_fires_on_a_real_row() {
2627 let id = file_path_to_id("x.md", "specs");
2628 let (_, warnings) = parse_relationships_with_warnings(
2629 "- **REFERENCES**: [[alpha]] -- not an em dash\n",
2630 "specs",
2631 Some(&id),
2632 );
2633 assert_eq!(warnings.len(), 1, "{warnings:?}");
2634 }
2635
2636 #[test]
2644 fn frontmatter_never_opens_a_code_block_over_the_body() {
2645 for fm in [
2646 "notes: |\n ```rust",
2647 "notes: |\n ~~~",
2648 "notes: |\n ```\n still open",
2649 "notes: |\n indented block\n",
2650 ] {
2651 let md = format!(
2652 "---\ntype: spec\n{fm}\n---\n\n# Real Title\n\n## Identity\n\nSee [[a-link]].\n"
2653 );
2654 let r = parse_markdown(&md, "fm-test.md", &spec_schema(), "specs").unwrap();
2655 assert_eq!(
2656 r.entity.title, "Real Title",
2657 "frontmatter ate the title: {fm:?}"
2658 );
2659 assert_eq!(
2660 headings(&r),
2661 vec!["Identity"],
2662 "frontmatter ate the sections: {fm:?}"
2663 );
2664 assert_eq!(
2665 link_targets(&r),
2666 vec!["specs--a-link".to_string()],
2667 "frontmatter ate the links: {fm:?}"
2668 );
2669 }
2670 }
2671}