memstead_base/engine/export_llms_txt.rs
1//! Render one mem as a single agent-readable Markdown document — the
2//! `/llms-full.txt` shape, shared by the served endpoint and
3//! `memstead export --format llms-txt`.
4//!
5//! The document is built to be *swallowed whole*: an agent whose goal is
6//! "understand this graph fast" reads one document instead of walking the
7//! graph entity by entity. That is why the shape is what it is — every
8//! non-stub entity exactly once, in stable order, with its type visible and
9//! its references resolved to links that work from inside the flat document.
10//!
11//! **This lives in the engine so the served and exported documents cannot
12//! drift.** It was previously deployment-local, and matching the deployed
13//! shape by copying it would have made "matches" a snapshot rather than a
14//! property: two copies of a document shape is exactly how a divergence
15//! starts. One renderer, two callers.
16//!
17//! Stubs never appear. A stub is the engine's placeholder for an unresolved
18//! reference, not content, and the document's own header promises every
19//! non-stub entity — so rendering one would make the header false.
20//!
21//! Empty sections are kept verbatim. An explicitly empty slot is signal to an
22//! agent: it says the schema asks for this and nobody has answered, which is
23//! different from the section not existing.
24
25use crate::entity::EntityId;
26use crate::render;
27
28/// Deployment-supplied inputs to the document header.
29///
30/// Everything here is context the *renderer* cannot know: who is serving the
31/// document and what else the reader should be pointed at. A CLI export has no
32/// deployment identity, so these are optional rather than defaulted — a header
33/// that invents an authority would be lying about provenance, which is the one
34/// thing this document exists to state plainly.
35#[derive(Debug, Clone, Default)]
36pub struct LlmsTxtContext {
37 /// The serving authority (a host). `None` for a CLI export, whose header
38 /// names the mem instead — no deployment is vouching for the bytes.
39 pub authority: Option<String>,
40 /// Absolute link prefix (origin + any gate prefix). Empty renders entity
41 /// references as the relative `entity/<id>`, which is what a document
42 /// exported to a file wants.
43 pub href_prefix: String,
44 /// Cross-origin links the serving surface wants an agent to see. Empty
45 /// omits the block entirely — a user exporting their own mem is not
46 /// advertising someone else's project.
47 pub wider_project: Vec<(String, String)>,
48}
49
50/// A markdown link for one entity. `[` / `]` in a title would break the link
51/// text, so they are folded to parentheses rather than escaped — the title is
52/// display text here, not data being round-tripped.
53pub fn entity_md_link(href_prefix: &str, id: &str, title: &str) -> String {
54 let text = title.replace('[', "(").replace(']', ")");
55 if href_prefix.is_empty() {
56 format!("[{text}](entity/{id})")
57 } else {
58 format!("[{text}]({href_prefix}/entity/{id})")
59 }
60}
61
62/// Drop the frontmatter block the shared entity render emits. The flat
63/// document surfaces the type as a visible line instead; the rest of the
64/// frontmatter is agent-budget metadata that would be noise repeated once per
65/// entity.
66///
67/// The split is the core's ([`crate::frontmatter_parts`]); this only
68/// normalises the body's line endings and drops the blank run after the
69/// closing fence, as the flat document always did. A document with no
70/// closed frontmatter is returned untouched.
71pub fn strip_frontmatter(md: &str) -> String {
72 match crate::frontmatter_parts(md) {
73 Some((_, body)) => body
74 .lines()
75 .collect::<Vec<_>>()
76 .join("\n")
77 .trim_start_matches('\n')
78 .to_string(),
79 None => md.to_string(),
80 }
81}
82
83/// Rewrite `[[…]]` wiki-links to markdown links, resolving each occurrence
84/// under a three-rule precedence:
85///
86/// 1. **Qualified references** — the dash form (`[[mem--slug]]`) and the
87/// canonical colon form (`[[mem:slug]]`, the grammar's cross-mem shape,
88/// which hierarchical mems can only write this way) — unambiguous,
89/// always resolve; a qualified miss never falls through to the slug
90/// passes, because the author named a mem.
91/// 2. **Local bare slugs** — a slug present in the source mem binds there,
92/// however many other mems reuse it. That is the engine's authoring
93/// semantics: a bare wiki-link is a same-mem reference.
94/// 3. **Foreign bare slugs** — a slug owned by exactly one *other* mem
95/// resolves to it; a slug two foreign mems both own **stays raw text**.
96/// Guessing between them would fabricate a reference the author never
97/// made, and a visibly unresolved `[[slug]]` is the honest output.
98///
99/// **Code is never rewritten.** Resolution scans the engine's masked view —
100/// the same one every other reader uses — and slices from the original, so a
101/// fenced or inline code sample documenting wiki-link syntax comes out
102/// byte-identical. A hand-rolled string walk without masking is exactly the
103/// defect the HTML exporter was fixed for; sharing the masked view is what
104/// stops this renderer reintroducing it.
105///
106/// `id_titles` must contain **no stubs**. A stub is an unresolved reference
107/// the engine materialised, not content — and this document excludes stubs,
108/// so resolving a link to one would emit a link to a page the document itself
109/// does not contain. Worse, because an engine-authored bare wiki-link creates
110/// a *local* stub, stubs in the map make rule 2 match every bare slug and
111/// rules 3's foreign passes unreachable.
112pub fn linkify_wikilinks(
113 body: String,
114 id_titles: &[(String, String)],
115 href_prefix: &str,
116 source_mem: &str,
117) -> String {
118 let mut by_id: std::collections::HashMap<&str, &str> = std::collections::HashMap::new();
119 let mut local: std::collections::HashMap<&str, (&str, &str)> = std::collections::HashMap::new();
120 let mut foreign: std::collections::HashMap<&str, Option<(&str, &str)>> =
121 std::collections::HashMap::new();
122 for (id, title) in id_titles {
123 by_id.insert(id.as_str(), title.as_str());
124 if let Some((mem, slug)) = id.split_once("--") {
125 if mem == source_mem {
126 local.insert(slug, (id.as_str(), title.as_str()));
127 } else {
128 foreign
129 .entry(slug)
130 .and_modify(|e| *e = None)
131 .or_insert(Some((id.as_str(), title.as_str())));
132 }
133 }
134 }
135
136 let resolve = |target: &str| -> Option<(String, String)> {
137 if let Some(title) = by_id.get(target) {
138 return Some((target.to_string(), title.to_string()));
139 }
140 // The canonical colon form (`mem:slug`) is the same qualified
141 // reference as the dash form one grammar tier over — the entity
142 // parser and both wiki-link decoders read it, and hierarchical mems
143 // can only be referenced this way. Canonicalise and look up; a miss
144 // stays a miss, because the author named a mem and guessing a slug
145 // pass instead would rebind the reference.
146 if !target.contains("::")
147 && let Some((prefix, slug)) = target.split_once(':')
148 && !prefix.is_empty()
149 && !slug.is_empty()
150 {
151 let id = crate::entity::EntityId::new(prefix, slug);
152 return by_id
153 .get(id.as_ref())
154 .map(|title| (id.to_string(), title.to_string()));
155 }
156 if let Some((id, title)) = local.get(target) {
157 return Some((id.to_string(), title.to_string()));
158 }
159 // `Some(None)` is an ambiguous foreign slug — deliberately unresolved.
160 foreign
161 .get(target)
162 .copied()
163 .flatten()
164 .map(|(id, title)| (id.to_string(), title.to_string()))
165 };
166
167 // Offsets come from the masked view; every byte emitted comes from the
168 // original, so masking can only change WHICH spans are rewritten, never
169 // the bytes of the ones that are not.
170 let masked = crate::markdown::mask_code_blocks_and_spans(&body);
171 let mut out = String::with_capacity(body.len());
172 let mut cursor = 0usize;
173 let bytes = masked.as_bytes();
174 let mut i = 0usize;
175 while i + 1 < bytes.len() {
176 if bytes[i] == b'['
177 && bytes[i + 1] == b'['
178 && let Some(rel) = masked[i + 2..].find("]]")
179 {
180 let inner_start = i + 2;
181 let inner_end = inner_start + rel;
182 // The link text is read from the ORIGINAL: the masked view is
183 // only a map of where code is.
184 let inner = &body[inner_start..inner_end];
185 // Only the TARGET half resolves; an author-supplied label wins
186 // as link text, because that is what the author chose a reader
187 // to see. Target normalisation is the decoders' own
188 // `strip_wiki_link_decorations` — `|label`, `#anchor`, `../`,
189 // `.md` — so this renderer reads exactly the grammar the parser
190 // and validators read, no form less. Two rounds of the same
191 // leak (the aliased form, then the colon form) came from
192 // hand-rolling a subset of it here.
193 let label = inner.split_once('|').map(|(_, l)| l.trim());
194 let target = crate::entity::id::strip_wiki_link_decorations(inner);
195 out.push_str(&body[cursor..i]);
196 match resolve(&target) {
197 Some((id, title)) => {
198 out.push_str(&entity_md_link(href_prefix, &id, label.unwrap_or(&title)))
199 }
200 // Unresolvable: name it as PLAIN TEXT — never a link, never
201 // surviving `[[…]]` syntax.
202 //
203 // A link would invent a target: for an ambiguous foreign slug
204 // it would pick one of two arbitrarily, and for a stub target
205 // it would point at a page this document deliberately
206 // excludes. Leaving the brackets would put internal wiki-link
207 // syntax in front of a reader the header promised a
208 // self-contained document to. Plain text is the third option,
209 // and the only one that is neither a guess nor a leak.
210 // Print the label when the author gave one, else the target —
211 // never the raw `target|label` span, which would put an
212 // internal id and a pipe in front of the reader.
213 None => out.push_str(label.unwrap_or(&target)),
214 }
215 cursor = inner_end + 2;
216 i = inner_end + 2;
217 continue;
218 }
219 i += 1;
220 }
221 out.push_str(&body[cursor..]);
222 out
223}
224
225impl crate::Engine {
226 /// Render `mem` as one Markdown document in the `/llms-full.txt` shape.
227 ///
228 /// Refuses an unmounted mem with [`EngineError::UnknownMem`] rather than
229 /// emitting an empty document — a document that says "Entities: 0" about a
230 /// mem this workspace never mounted is a confident wrong answer, and the
231 /// caller can tell the two apart only if the engine does.
232 ///
233 /// [`EngineError::UnknownMem`]: crate::engine::EngineError::UnknownMem
234 pub fn render_llms_txt(
235 &self,
236 mem: &str,
237 ctx: &LlmsTxtContext,
238 ) -> Result<String, crate::engine::EngineError> {
239 self.render_llms_txt_scoped(mem, ctx, None)
240 }
241
242 /// [`Self::render_llms_txt`] reduced to a chain: only the mem's
243 /// entities in `chain` are rendered, wiki-links to entities outside
244 /// it stay raw (unresolved), and the header names the chain. `None`
245 /// is the whole mem, byte-identical to the unscoped document.
246 pub fn render_llms_txt_scoped(
247 &self,
248 mem: &str,
249 ctx: &LlmsTxtContext,
250 chain: Option<&crate::graph::chain::ChainSet>,
251 ) -> Result<String, crate::engine::EngineError> {
252 let mounted = self
253 .mounts
254 .iter()
255 .find(|m| m.mount.mem == mem)
256 .ok_or_else(|| crate::engine::EngineError::UnknownMem(mem.to_string()))?;
257
258 let schema_pin = mounted
259 .mount
260 .schema
261 .as_ref()
262 .map(|s| s.as_display())
263 .unwrap_or_default();
264 let config = self.mem_config_for(mem);
265 let subject = config
266 .and_then(|c| c.description.clone())
267 .unwrap_or_else(|| mem.to_string());
268 // The provenance line says who vouches. With an authority that is the
269 // deployment; without one it is the workspace the export came from.
270 // Printing "this deployment vouches" into a file exported from a
271 // laptop would make the header's one load-bearing sentence false.
272 let provenance = match (self.mem_origin_class(mem), ctx.authority.is_some()) {
273 (crate::render::OriginClass::FirstParty, true) => {
274 "first-party (this deployment vouches for the content as its own)"
275 }
276 (crate::render::OriginClass::ThirdParty, true) => {
277 "third-party (this deployment does not vouch for the content)"
278 }
279 (crate::render::OriginClass::FirstParty, false) => {
280 "first-party (authored in the workspace this export came from)"
281 }
282 (crate::render::OriginClass::ThirdParty, false) => {
283 "third-party (a read-only mount — someone else's published content)"
284 }
285 };
286
287 // Every non-stub entity of THIS mem, once, in stable id order —
288 // reduced to the chain when one is given. The link table is
289 // reduced the same way, so a link to an entity outside the chain
290 // stays raw text rather than pointing at a page this document
291 // does not contain.
292 let mut id_titles = self.entity_id_titles();
293 if let Some(chain) = chain {
294 id_titles.retain(|(id, _)| chain.contains(&EntityId::canonical(id)));
295 }
296 let mut ids: Vec<String> = self
297 .store
298 .all_entities()
299 .filter(|e| e.mem == mem && !e.stub && chain.is_none_or(|c| c.contains(&e.id)))
300 .map(|e| e.id.to_string())
301 .collect();
302 ids.sort();
303 let count = ids.len();
304 let chain_line = chain
305 .map(|c| format!("Chain: {}\n", c.describe()))
306 .unwrap_or_default();
307
308 // The header names an authority only when one is serving. A CLI export
309 // names the mem: no deployment is vouching for these bytes, and saying
310 // otherwise would put a false provenance line at the top of the one
311 // document written to be read whole and believed.
312 let heading = match &ctx.authority {
313 Some(a) => format!("# {a} — {subject}\n\nAuthority: {a}\n"),
314 // A mem with no description falls back to its own name as the
315 // subject, which would render "# srcmem — srcmem". Say it once.
316 None if subject == mem => format!("# {mem}\n\nMem: {mem}\n"),
317 None => format!("# {mem} — {subject}\n\nMem: {mem}\n"),
318 };
319 let wider = if ctx.wider_project.is_empty() {
320 String::new()
321 } else {
322 let lines: String = ctx
323 .wider_project
324 .iter()
325 .map(|(url, what)| format!("- {url} — {what}.\n"))
326 .collect();
327 // Trailing blank line: the served document has always had one
328 // between the list and the closing sentence, and without it the
329 // sentence becomes a lazy continuation of the last list item in
330 // Markdown. A `contains`-based test cannot see the difference,
331 // which is exactly why it went unnoticed.
332 format!("The wider project:\n{lines}\n")
333 };
334 let links_sentence = if ctx.href_prefix.is_empty() {
335 "Entity references are relative links to that entity's own page."
336 } else {
337 "Entity references are absolute links to that entity's own page."
338 };
339
340 let scope_sentence = if chain.is_some() {
341 "Every non-stub entity of this Memstead graph that the chain above reaches follows, \
342 once, with its type and sections; references to entities outside the chain are left \
343 as raw wiki-links."
344 } else {
345 "Every non-stub entity of this Memstead graph follows, once, with its type and \
346 sections."
347 };
348 let mut out = format!(
349 "{heading}\
350Subject: {subject}\n\
351Schema: {schema_pin}\n\
352{chain_line}\
353Entities: {count}\n\
354Provenance: {provenance}\n\n\
355{wider}\
356{scope_sentence} {links_sentence}\n\n\
357---\n\n"
358 );
359
360 for id in &ids {
361 let Some(entity) = self.get_entity(&EntityId::canonical(id)) else {
362 continue;
363 };
364 let md = strip_frontmatter(&render::render_entity_markdown(entity, None));
365 let typed = match md.split_once('\n') {
366 Some((title_line, rest)) => format!(
367 "{title_line}\n\n_Type: {}_\n\n{}",
368 entity.entity_type,
369 rest.trim_start_matches('\n')
370 ),
371 None => format!("{md}\n\n_Type: {}_", entity.entity_type),
372 };
373 out.push_str(&linkify_wikilinks(typed, &id_titles, &ctx.href_prefix, mem));
374 if !out.ends_with('\n') {
375 out.push('\n');
376 }
377 out.push_str("\n---\n\n");
378 }
379
380 Ok(out)
381 }
382
383 /// `(id, title)` for every entity in the store — the lookup the link
384 /// rewriter needs. Workspace-wide on purpose: a wiki-link may reach into
385 /// another mounted mem, and resolving it is what makes the flat document
386 /// navigable.
387 fn entity_id_titles(&self) -> Vec<(String, String)> {
388 // Stubs are excluded. This document omits stub entities, so linking to
389 // one would point at a page the document does not contain — and since
390 // an engine-authored bare wiki-link materialises a LOCAL stub, leaving
391 // stubs in would make every bare slug resolve locally and the
392 // foreign-slug rules unreachable.
393 let mut out: Vec<(String, String)> = self
394 .store
395 .all_entities()
396 .filter(|e| !e.stub)
397 .map(|e| (e.id.to_string(), e.title.clone()))
398 .collect();
399 out.sort();
400 out
401 }
402}
403
404#[cfg(test)]
405mod tests {
406 use super::*;
407
408 fn titles() -> Vec<(String, String)> {
409 vec![
410 ("engine--mem".to_string(), "Mem".to_string()),
411 ("flagship--mem".to_string(), "Mem".to_string()),
412 ("engine--pipeline".to_string(), "Pipeline".to_string()),
413 ]
414 }
415
416 /// The three passes, and their precedence. A full id always resolves; a
417 /// bare slug binds mem-locally first (the engine's authoring semantics);
418 /// and a slug two FOREIGN mems both own stays raw text rather than being
419 /// guessed — a fabricated reference the author never made is worse than a
420 /// visibly unresolved one.
421 #[test]
422 fn wiki_links_resolve_in_three_passes_and_never_guess() {
423 let t = titles();
424
425 // Pass 1 — full id.
426 assert_eq!(
427 linkify_wikilinks("See [[engine--pipeline]].".to_string(), &t, "", "engine"),
428 "See [Pipeline](entity/engine--pipeline)."
429 );
430
431 // Pass 3 wins over pass 2 — the slug exists locally, so it binds
432 // locally however many other mems reuse it.
433 assert_eq!(
434 linkify_wikilinks("A [[mem]].".to_string(), &t, "", "engine"),
435 "A [Mem](entity/engine--mem)."
436 );
437 assert_eq!(
438 linkify_wikilinks("A [[mem]].".to_string(), &t, "", "flagship"),
439 "A [Mem](entity/flagship--mem)."
440 );
441
442 // Pass 2 — unique in exactly one foreign mem, so it resolves.
443 assert_eq!(
444 linkify_wikilinks("A [[pipeline]].".to_string(), &t, "", "flagship"),
445 "A [Pipeline](entity/engine--pipeline)."
446 );
447
448 // Ambiguous across two FOREIGN mems and absent locally: named, not
449 // guessed — and not left as wiki-link syntax either.
450 assert_eq!(
451 linkify_wikilinks("A [[mem]].".to_string(), &t, "", "plugin"),
452 "A mem.",
453 "an ambiguous foreign slug degrades to plain text, never a guess"
454 );
455 }
456
457 /// Exactly two link forms exist, selected by whether a base is given.
458 /// A third — root-relative `/entity/<id>` — must never appear: the
459 /// document is read both from a file and from a served page, and only
460 /// these two work in both places.
461 #[test]
462 fn only_two_link_forms_are_emitted() {
463 let t = titles();
464 let rel = linkify_wikilinks("[[engine--mem]]".to_string(), &t, "", "engine");
465 assert_eq!(rel, "[Mem](entity/engine--mem)");
466 assert!(!rel.contains("(/entity/"), "never root-relative: {rel}");
467
468 let abs = linkify_wikilinks(
469 "[[engine--mem]]".to_string(),
470 &t,
471 "https://example.com",
472 "engine",
473 );
474 assert_eq!(abs, "[Mem](https://example.com/entity/engine--mem)");
475 }
476
477 /// A title carrying brackets would break the markdown link text, so they
478 /// fold to parentheses. The link target is unaffected.
479 #[test]
480 fn bracketed_titles_cannot_break_the_link() {
481 let t = vec![("m--x".to_string(), "A [bracketed] title".to_string())];
482 assert_eq!(
483 linkify_wikilinks("[[m--x]]".to_string(), &t, "", "m"),
484 "[A (bracketed) title](entity/m--x)"
485 );
486 }
487
488 /// Wiki-link syntax inside code is documentation, not a reference. A
489 /// fenced block or inline span showing `[[slug]]` must come out
490 /// byte-identical — the defect the HTML exporter was fixed for, which a
491 /// hand-rolled string walk reintroduces the moment nobody checks.
492 #[test]
493 fn code_spans_and_fences_are_never_rewritten() {
494 let t = titles();
495 let body = "Prose [[engine--mem]] resolves.\n\n\
496 Inline `[[engine--mem]]` does not.\n\n\
497 ```\n[[engine--mem]]\n```\n";
498 let out = linkify_wikilinks(body.to_string(), &t, "", "engine");
499
500 assert!(
501 out.contains("Prose [Mem](entity/engine--mem) resolves."),
502 "prose still resolves: {out}"
503 );
504 assert!(
505 out.contains("Inline `[[engine--mem]]` does not."),
506 "an inline code span is left alone: {out}"
507 );
508 assert!(
509 out.contains("```\n[[engine--mem]]\n```"),
510 "a fenced block is left alone: {out}"
511 );
512 }
513
514 /// The engine's grammar has three wiki-link forms and this renderer must
515 /// read all of them. Only the target half resolves; an author-supplied
516 /// label is what a reader sees, and a `#Section` suffix addresses within
517 /// the target rather than naming a different one.
518 ///
519 /// Passing the whole span to the resolver made every aliased reference
520 /// miss and fall to the plain-text arm — printing the internal id and the
521 /// pipe into prose, precisely where the author had written a label.
522 #[test]
523 fn alias_and_anchor_wiki_link_forms_resolve() {
524 let t = titles();
525
526 // `[[target|label]]` — resolves, and the LABEL is the link text.
527 assert_eq!(
528 linkify_wikilinks("See [[engine--mem|the mem]].".to_string(), &t, "", "engine"),
529 "See [the mem](entity/engine--mem)."
530 );
531 // `[[target#Section]]` — the anchor addresses within the target.
532 assert_eq!(
533 linkify_wikilinks(
534 "See [[engine--mem#Identity]].".to_string(),
535 &t,
536 "",
537 "engine"
538 ),
539 "See [Mem](entity/engine--mem)."
540 );
541 // Both at once, and on a bare slug rather than a full id.
542 assert_eq!(
543 linkify_wikilinks("See [[mem#Identity|here]].".to_string(), &t, "", "engine"),
544 "See [here](entity/engine--mem)."
545 );
546 // Unresolvable WITH a label: the reader gets the label, never the
547 // internal target or the pipe.
548 assert_eq!(
549 linkify_wikilinks("See [[ghost|that thing]].".to_string(), &t, "", "engine"),
550 "See that thing."
551 );
552 }
553
554 /// The canonical colon cross-mem form (`[[mem:slug]]`) is a qualified
555 /// reference like the dash form — the grammar's own shape for it, and
556 /// the only one a hierarchical mem can be written in. It resolves to
557 /// the same target, an author label still wins as link text, and a miss
558 /// degrades to plain text WITHOUT falling through to the slug passes:
559 /// the author named a mem, and rebinding the slug elsewhere would be a
560 /// guess. The body of a live mem carried exactly this form into prose
561 /// as unresolved text when only `|` and `#` were hand-stripped here.
562 #[test]
563 fn colon_cross_mem_form_resolves_as_a_qualified_reference() {
564 let t = titles();
565
566 assert_eq!(
567 linkify_wikilinks("See [[flagship:mem]].".to_string(), &t, "", "engine"),
568 "See [Mem](entity/flagship--mem)."
569 );
570 assert_eq!(
571 linkify_wikilinks(
572 "See [[engine:mem|the mem]].".to_string(),
573 &t,
574 "",
575 "flagship"
576 ),
577 "See [the mem](entity/engine--mem)."
578 );
579 // A colon miss is a miss: `pipeline` is unique in a foreign mem, but
580 // the author qualified it into a mem that does not own it.
581 assert_eq!(
582 linkify_wikilinks("See [[flagship:pipeline]].".to_string(), &t, "", "engine"),
583 "See flagship:pipeline."
584 );
585 }
586
587 /// A reference to nothing is named in plain text — the same treatment an
588 /// ambiguous foreign slug gets, for the same reason: say what could not be
589 /// resolved without inventing a target, and without leaking internal
590 /// wiki-link syntax into a document promised as self-contained.
591 ///
592 /// The one place `[[…]]` legitimately survives is inside code, which is
593 /// never rewritten at all.
594 #[test]
595 fn an_unresolvable_reference_degrades_to_plain_text() {
596 let t = titles();
597 assert_eq!(
598 linkify_wikilinks("See [[ghost]].".to_string(), &t, "", "engine"),
599 "See ghost."
600 );
601 // A full id whose target is a stub is the same case: stubs are absent
602 // from the map by design, so the reference cannot resolve — and this
603 // is the shape the auto-generated `## Relationships` block emits.
604 assert_eq!(
605 linkify_wikilinks(
606 "- **USES**: [[engine--phantom]]".to_string(),
607 &t,
608 "",
609 "engine"
610 ),
611 "- **USES**: engine--phantom"
612 );
613 }
614
615 /// Frontmatter is dropped; a body that has none is returned untouched.
616 #[test]
617 fn frontmatter_is_stripped_only_when_present() {
618 assert_eq!(
619 strip_frontmatter("---\ntype: spec\n---\n\n# Title\n\nBody."),
620 "# Title\n\nBody."
621 );
622 assert_eq!(strip_frontmatter("# Title\n\nBody."), "# Title\n\nBody.");
623 // An unterminated block is not frontmatter — returning the body
624 // half-eaten would silently lose content.
625 assert_eq!(strip_frontmatter("---\nno close"), "---\nno close");
626 }
627}