Skip to main content

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 mem_class = self.mem_origin_class(mem);
273        let provenance = match (mem_class, ctx.authority.is_some()) {
274            (crate::render::OriginClass::FirstParty, true) => {
275                "first-party (this deployment vouches for the content as its own)"
276            }
277            (crate::render::OriginClass::ThirdParty, true) => {
278                "third-party (this deployment does not vouch for the content)"
279            }
280            (crate::render::OriginClass::FirstParty, false) => {
281                "first-party (authored in the workspace this export came from)"
282            }
283            (crate::render::OriginClass::ThirdParty, false) => {
284                "third-party (a read-only mount — someone else's published content)"
285            }
286        };
287
288        // Every non-stub entity of THIS mem, once, in stable id order —
289        // reduced to the chain when one is given. The link table is
290        // reduced the same way, so a link to an entity outside the chain
291        // stays raw text rather than pointing at a page this document
292        // does not contain.
293        let mut id_titles = self.entity_id_titles();
294        if let Some(chain) = chain {
295            id_titles.retain(|(id, _)| chain.contains(&EntityId::canonical(id)));
296        }
297        let mut ids: Vec<String> = self
298            .store
299            .all_entities()
300            .filter(|e| e.mem == mem && !e.stub && chain.is_none_or(|c| c.contains(&e.id)))
301            .map(|e| e.id.to_string())
302            .collect();
303        ids.sort();
304        let count = ids.len();
305        let chain_line = chain
306            .map(|c| format!("Chain: {}\n", c.describe()))
307            .unwrap_or_default();
308
309        // The header names an authority only when one is serving. A CLI export
310        // names the mem: no deployment is vouching for these bytes, and saying
311        // otherwise would put a false provenance line at the top of the one
312        // document written to be read whole and believed.
313        let heading = match &ctx.authority {
314            Some(a) => format!("# {a} — {subject}\n\nAuthority: {a}\n"),
315            // A mem with no description falls back to its own name as the
316            // subject, which would render "# srcmem — srcmem". Say it once.
317            None if subject == mem => format!("# {mem}\n\nMem: {mem}\n"),
318            None => format!("# {mem} — {subject}\n\nMem: {mem}\n"),
319        };
320        let wider = if ctx.wider_project.is_empty() {
321            String::new()
322        } else {
323            let lines: String = ctx
324                .wider_project
325                .iter()
326                .map(|(url, what)| format!("- {url} — {what}.\n"))
327                .collect();
328            // Trailing blank line: the served document has always had one
329            // between the list and the closing sentence, and without it the
330            // sentence becomes a lazy continuation of the last list item in
331            // Markdown. A `contains`-based test cannot see the difference,
332            // which is exactly why it went unnoticed.
333            format!("The wider project:\n{lines}\n")
334        };
335        let links_sentence = if ctx.href_prefix.is_empty() {
336            "Entity references are relative links to that entity's own page."
337        } else {
338            "Entity references are absolute links to that entity's own page."
339        };
340
341        let scope_sentence = if chain.is_some() {
342            "Every non-stub entity of this Memstead graph that the chain above reaches follows, \
343             once, with its type and sections; references to entities outside the chain are left \
344             as raw wiki-links."
345        } else {
346            "Every non-stub entity of this Memstead graph follows, once, with its type and \
347             sections."
348        };
349        let mut out = format!(
350            "{heading}\
351Subject: {subject}\n\
352Schema: {schema_pin}\n\
353{chain_line}\
354Entities: {count}\n\
355Provenance: {provenance}\n\n\
356{wider}\
357{scope_sentence} {links_sentence}\n\n\
358---\n\n"
359        );
360
361        for id in &ids {
362            let Some(entity) = self.get_entity(&EntityId::canonical(id)) else {
363                continue;
364            };
365            let md = strip_frontmatter(&render::render_entity_markdown(entity, None));
366            let typed = match md.split_once('\n') {
367                Some((title_line, rest)) => format!(
368                    "{title_line}\n\n_Type: {}_\n\n{}",
369                    entity.entity_type,
370                    rest.trim_start_matches('\n')
371                ),
372                None => format!("{md}\n\n_Type: {}_", entity.entity_type),
373            };
374            let linked = linkify_wikilinks(typed, &id_titles, &ctx.href_prefix, mem);
375            // The header's `Provenance:` line vouches for the document as a
376            // whole, which is the wrong grain for one merged contribution:
377            // this document is read whole and believed, so a body adopted
378            // from a fork is contained inline. Only where the entity's class
379            // differs from the mem's — in a mem the header already declares
380            // third-party, wrapping every entity would repeat the header
381            // once per entity and tell a reader nothing new, and a mem with
382            // no adopted body exports byte-identically to before.
383            let entity_class = self.entity_origin_class(&entity.id);
384            let contained = entity_class.is_third_party() && !mem_class.is_third_party();
385            out.push_str(&if contained {
386                crate::render::quote_wrap(&linked, &crate::render::quote_marker(&linked))
387            } else {
388                linked
389            });
390            if !out.ends_with('\n') {
391                out.push('\n');
392            }
393            out.push_str("\n---\n\n");
394        }
395
396        Ok(out)
397    }
398
399    /// `(id, title)` for every entity in the store — the lookup the link
400    /// rewriter needs. Workspace-wide on purpose: a wiki-link may reach into
401    /// another mounted mem, and resolving it is what makes the flat document
402    /// navigable.
403    fn entity_id_titles(&self) -> Vec<(String, String)> {
404        // Stubs are excluded. This document omits stub entities, so linking to
405        // one would point at a page the document does not contain — and since
406        // an engine-authored bare wiki-link materialises a LOCAL stub, leaving
407        // stubs in would make every bare slug resolve locally and the
408        // foreign-slug rules unreachable.
409        let mut out: Vec<(String, String)> = self
410            .store
411            .all_entities()
412            .filter(|e| !e.stub)
413            .map(|e| (e.id.to_string(), e.title.clone()))
414            .collect();
415        out.sort();
416        out
417    }
418}
419
420#[cfg(test)]
421mod tests {
422    use super::*;
423
424    fn titles() -> Vec<(String, String)> {
425        vec![
426            ("engine--mem".to_string(), "Mem".to_string()),
427            ("flagship--mem".to_string(), "Mem".to_string()),
428            ("engine--pipeline".to_string(), "Pipeline".to_string()),
429        ]
430    }
431
432    /// The three passes, and their precedence. A full id always resolves; a
433    /// bare slug binds mem-locally first (the engine's authoring semantics);
434    /// and a slug two FOREIGN mems both own stays raw text rather than being
435    /// guessed — a fabricated reference the author never made is worse than a
436    /// visibly unresolved one.
437    #[test]
438    fn wiki_links_resolve_in_three_passes_and_never_guess() {
439        let t = titles();
440
441        // Pass 1 — full id.
442        assert_eq!(
443            linkify_wikilinks("See [[engine--pipeline]].".to_string(), &t, "", "engine"),
444            "See [Pipeline](entity/engine--pipeline)."
445        );
446
447        // Pass 3 wins over pass 2 — the slug exists locally, so it binds
448        // locally however many other mems reuse it.
449        assert_eq!(
450            linkify_wikilinks("A [[mem]].".to_string(), &t, "", "engine"),
451            "A [Mem](entity/engine--mem)."
452        );
453        assert_eq!(
454            linkify_wikilinks("A [[mem]].".to_string(), &t, "", "flagship"),
455            "A [Mem](entity/flagship--mem)."
456        );
457
458        // Pass 2 — unique in exactly one foreign mem, so it resolves.
459        assert_eq!(
460            linkify_wikilinks("A [[pipeline]].".to_string(), &t, "", "flagship"),
461            "A [Pipeline](entity/engine--pipeline)."
462        );
463
464        // Ambiguous across two FOREIGN mems and absent locally: named, not
465        // guessed — and not left as wiki-link syntax either.
466        assert_eq!(
467            linkify_wikilinks("A [[mem]].".to_string(), &t, "", "plugin"),
468            "A mem.",
469            "an ambiguous foreign slug degrades to plain text, never a guess"
470        );
471    }
472
473    /// Exactly two link forms exist, selected by whether a base is given.
474    /// A third — root-relative `/entity/<id>` — must never appear: the
475    /// document is read both from a file and from a served page, and only
476    /// these two work in both places.
477    #[test]
478    fn only_two_link_forms_are_emitted() {
479        let t = titles();
480        let rel = linkify_wikilinks("[[engine--mem]]".to_string(), &t, "", "engine");
481        assert_eq!(rel, "[Mem](entity/engine--mem)");
482        assert!(!rel.contains("(/entity/"), "never root-relative: {rel}");
483
484        let abs = linkify_wikilinks(
485            "[[engine--mem]]".to_string(),
486            &t,
487            "https://example.com",
488            "engine",
489        );
490        assert_eq!(abs, "[Mem](https://example.com/entity/engine--mem)");
491    }
492
493    /// A title carrying brackets would break the markdown link text, so they
494    /// fold to parentheses. The link target is unaffected.
495    #[test]
496    fn bracketed_titles_cannot_break_the_link() {
497        let t = vec![("m--x".to_string(), "A [bracketed] title".to_string())];
498        assert_eq!(
499            linkify_wikilinks("[[m--x]]".to_string(), &t, "", "m"),
500            "[A (bracketed) title](entity/m--x)"
501        );
502    }
503
504    /// Wiki-link syntax inside code is documentation, not a reference. A
505    /// fenced block or inline span showing `[[slug]]` must come out
506    /// byte-identical — the defect the HTML exporter was fixed for, which a
507    /// hand-rolled string walk reintroduces the moment nobody checks.
508    #[test]
509    fn code_spans_and_fences_are_never_rewritten() {
510        let t = titles();
511        let body = "Prose [[engine--mem]] resolves.\n\n\
512             Inline `[[engine--mem]]` does not.\n\n\
513             ```\n[[engine--mem]]\n```\n";
514        let out = linkify_wikilinks(body.to_string(), &t, "", "engine");
515
516        assert!(
517            out.contains("Prose [Mem](entity/engine--mem) resolves."),
518            "prose still resolves: {out}"
519        );
520        assert!(
521            out.contains("Inline `[[engine--mem]]` does not."),
522            "an inline code span is left alone: {out}"
523        );
524        assert!(
525            out.contains("```\n[[engine--mem]]\n```"),
526            "a fenced block is left alone: {out}"
527        );
528    }
529
530    /// The engine's grammar has three wiki-link forms and this renderer must
531    /// read all of them. Only the target half resolves; an author-supplied
532    /// label is what a reader sees, and a `#Section` suffix addresses within
533    /// the target rather than naming a different one.
534    ///
535    /// Passing the whole span to the resolver made every aliased reference
536    /// miss and fall to the plain-text arm — printing the internal id and the
537    /// pipe into prose, precisely where the author had written a label.
538    #[test]
539    fn alias_and_anchor_wiki_link_forms_resolve() {
540        let t = titles();
541
542        // `[[target|label]]` — resolves, and the LABEL is the link text.
543        assert_eq!(
544            linkify_wikilinks("See [[engine--mem|the mem]].".to_string(), &t, "", "engine"),
545            "See [the mem](entity/engine--mem)."
546        );
547        // `[[target#Section]]` — the anchor addresses within the target.
548        assert_eq!(
549            linkify_wikilinks(
550                "See [[engine--mem#Identity]].".to_string(),
551                &t,
552                "",
553                "engine"
554            ),
555            "See [Mem](entity/engine--mem)."
556        );
557        // Both at once, and on a bare slug rather than a full id.
558        assert_eq!(
559            linkify_wikilinks("See [[mem#Identity|here]].".to_string(), &t, "", "engine"),
560            "See [here](entity/engine--mem)."
561        );
562        // Unresolvable WITH a label: the reader gets the label, never the
563        // internal target or the pipe.
564        assert_eq!(
565            linkify_wikilinks("See [[ghost|that thing]].".to_string(), &t, "", "engine"),
566            "See that thing."
567        );
568    }
569
570    /// The canonical colon cross-mem form (`[[mem:slug]]`) is a qualified
571    /// reference like the dash form — the grammar's own shape for it, and
572    /// the only one a hierarchical mem can be written in. It resolves to
573    /// the same target, an author label still wins as link text, and a miss
574    /// degrades to plain text WITHOUT falling through to the slug passes:
575    /// the author named a mem, and rebinding the slug elsewhere would be a
576    /// guess. The body of a live mem carried exactly this form into prose
577    /// as unresolved text when only `|` and `#` were hand-stripped here.
578    #[test]
579    fn colon_cross_mem_form_resolves_as_a_qualified_reference() {
580        let t = titles();
581
582        assert_eq!(
583            linkify_wikilinks("See [[flagship:mem]].".to_string(), &t, "", "engine"),
584            "See [Mem](entity/flagship--mem)."
585        );
586        assert_eq!(
587            linkify_wikilinks(
588                "See [[engine:mem|the mem]].".to_string(),
589                &t,
590                "",
591                "flagship"
592            ),
593            "See [the mem](entity/engine--mem)."
594        );
595        // A colon miss is a miss: `pipeline` is unique in a foreign mem, but
596        // the author qualified it into a mem that does not own it.
597        assert_eq!(
598            linkify_wikilinks("See [[flagship:pipeline]].".to_string(), &t, "", "engine"),
599            "See flagship:pipeline."
600        );
601    }
602
603    /// A reference to nothing is named in plain text — the same treatment an
604    /// ambiguous foreign slug gets, for the same reason: say what could not be
605    /// resolved without inventing a target, and without leaking internal
606    /// wiki-link syntax into a document promised as self-contained.
607    ///
608    /// The one place `[[…]]` legitimately survives is inside code, which is
609    /// never rewritten at all.
610    #[test]
611    fn an_unresolvable_reference_degrades_to_plain_text() {
612        let t = titles();
613        assert_eq!(
614            linkify_wikilinks("See [[ghost]].".to_string(), &t, "", "engine"),
615            "See ghost."
616        );
617        // A full id whose target is a stub is the same case: stubs are absent
618        // from the map by design, so the reference cannot resolve — and this
619        // is the shape the auto-generated `## Relationships` block emits.
620        assert_eq!(
621            linkify_wikilinks(
622                "- **USES**: [[engine--phantom]]".to_string(),
623                &t,
624                "",
625                "engine"
626            ),
627            "- **USES**: engine--phantom"
628        );
629    }
630
631    /// Frontmatter is dropped; a body that has none is returned untouched.
632    #[test]
633    fn frontmatter_is_stripped_only_when_present() {
634        assert_eq!(
635            strip_frontmatter("---\ntype: spec\n---\n\n# Title\n\nBody."),
636            "# Title\n\nBody."
637        );
638        assert_eq!(strip_frontmatter("# Title\n\nBody."), "# Title\n\nBody.");
639        // An unterminated block is not frontmatter — returning the body
640        // half-eaten would silently lose content.
641        assert_eq!(strip_frontmatter("---\nno close"), "---\nno close");
642    }
643}