memstead-base 0.26.1

Engine internals for Memstead — store, parser, validators, mem lifecycle, workspace policy. Published as a dependency of the memstead-cli and memstead-mcp products, not as a supported library — pre-1.0, no API stability promise.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! Wiki-link rewriter — shared lexical discipline with
//! [`crate::entity::parser::extract_inline_links`].
//!
//! Operates on the same masked-text model: CommonMark code blocks and
//! inline code spans are excluded from rewriting (matches inside them
//! remain bit-identical). Used by `Engine::rename_entity`'s
//! referrer-walk: [`rewrite_bare_slug`] rewrites same-mem
//! self-references and referrers, [`rewrite_cross_mem_slug`] rewrites
//! cross-mem referrers.

use regex::Regex;

/// Mask code blocks and inline code spans with spaces of equal length
/// so byte offsets in the masked text match the original.
///
/// One definition, shared with
/// [`crate::entity::parser::extract_inline_links`] and the strict
/// validator: a link the validator cannot see is a link this rewriter
/// does not touch and the extractor does not turn into an edge.
fn mask_for_link_scan(text: &str) -> String {
    crate::markdown::mask_code_blocks_and_spans(text)
}

/// [`mask_for_link_scan`] for a WHOLE entity file rather than a section
/// body: the frontmatter is left raw and only the body is masked, then
/// the two are rejoined.
///
/// Frontmatter is not markdown (see the [`crate::markdown`] header): a
/// YAML value that reads as a fence opener would otherwise mask the
/// body away, the scan would find no links, and the rewrite would
/// report zero changes on a file that needed them — a mem rename would
/// silently leave dangling cross-mem references behind. Masking
/// preserves byte length, so the rejoined view stays offset-aligned
/// with the original, which is what lets the rewriter splice by offset.
///
/// The split is done here rather than inside [`mask_for_link_scan`] on
/// purpose: a *section body* may legitimately open with a `---`
/// thematic break, which the frontmatter trim would mistake for a
/// frontmatter block and cut real content away. Only a caller that
/// knows it holds a whole file may trim.
fn mask_file_for_link_scan(text: &str) -> String {
    let body = crate::entity::parser::body_after_frontmatter(text);
    let frontmatter = &text[..text.len() - body.len()];
    format!("{frontmatter}{}", mask_for_link_scan(body))
}

/// Rewrite every same-mem `[[<old_slug>]]` (with or without a
/// `|label` suffix) in `text` to `[[<new_slug>]]`, preserving the
/// label and surrounding bytes verbatim. Wiki-links inside code
/// blocks or inline code spans are not touched.
///
/// Cross-mem forms (`[[<mem>:<slug>]]`, `[[<mem>--<slug>]]`)
/// are deliberately out of scope here — the renaming entity's own
/// body uses the bare-slug form for self-references, while external
/// referrer rewriting (which has its own mem prefix shape) is
/// handled by [`rewrite_cross_mem_slug`].
///
/// Returns the rewritten text and a count of how many matches were
/// rewritten (so callers can short-circuit when nothing changed).
pub(crate) fn rewrite_bare_slug(text: &str, old_slug: &str, new_slug: &str) -> (String, usize) {
    let masked = mask_for_link_scan(text);
    let link_re = Regex::new(r"\[\[([^\]]*)\]\]").unwrap();
    let mut out = String::with_capacity(text.len());
    let mut last_end = 0usize;
    let mut rewritten = 0usize;

    for cap in link_re.captures_iter(&masked) {
        let whole = cap.get(0).unwrap();
        let inner = cap.get(1).unwrap();
        // Map the masked-text slice back to the original — offsets
        // match by construction (mask_for_link_scan preserves them).
        let inner_str = &text[inner.start()..inner.end()];
        let (target, label) = match inner_str.find('|') {
            Some(i) => (&inner_str[..i], Some(&inner_str[i + 1..])),
            None => (inner_str, None),
        };

        out.push_str(&text[last_end..whole.start()]);
        // Compared as the decoder reads it: a leading `../`, a trailing
        // `.md` and a `#anchor` all name the same entity, so those links
        // are rewritten too, keeping their decorations.
        let (pre, core, post) = split_link_decorations(target);
        if core == old_slug {
            out.push_str("[[");
            out.push_str(pre);
            out.push_str(new_slug);
            out.push_str(post);
            if let Some(lbl) = label {
                out.push('|');
                out.push_str(lbl);
            }
            out.push_str("]]");
            rewritten += 1;
        } else {
            out.push_str(&text[whole.start()..whole.end()]);
        }
        last_end = whole.end();
    }
    out.push_str(&text[last_end..]);
    (out, rewritten)
}

/// Rewrite every cross-mem wiki-link in `text` whose mem half
/// matches `old_mem` and slug half matches `old_slug`, changing the
/// slug to `new_slug` and leaving the separator (`:` or `--`) and any
/// `|label` suffix intact. Both legal cross-mem forms are handled:
///
/// - `[[<old_mem>:<old_slug>]]` → `[[<old_mem>:<new_slug>]]`
/// - `[[<old_mem>--<old_slug>]]` → `[[<old_mem>--<new_slug>]]`
///
/// Matches inside code blocks and inline code spans are not
/// rewritten (same discipline as [`rewrite_bare_slug`]). Slug halves
/// that don't equal `old_slug` are left alone — this function only
/// rewrites the renamed entity's cross-mem references, not every
/// reference from `old_mem`.
///
/// Returns the rewritten text plus a count of how many matches were
/// changed.
pub(crate) fn rewrite_cross_mem_slug(
    text: &str,
    old_mem: &str,
    old_slug: &str,
    new_slug: &str,
) -> (String, usize) {
    let masked = mask_for_link_scan(text);
    let link_re = Regex::new(r"\[\[([^\]]*)\]\]").unwrap();
    let mut out = String::with_capacity(text.len());
    let mut last_end = 0usize;
    let mut rewritten = 0usize;

    for cap in link_re.captures_iter(&masked) {
        let whole = cap.get(0).unwrap();
        let inner = cap.get(1).unwrap();
        let inner_str = &text[inner.start()..inner.end()];
        let (target, label) = match inner_str.find('|') {
            Some(i) => (&inner_str[..i], Some(&inner_str[i + 1..])),
            None => (inner_str, None),
        };

        out.push_str(&text[last_end..whole.start()]);
        // Compared as the decoder reads it, decorations kept (see
        // `rewrite_bare_slug`).
        let (pre, target, post) = split_link_decorations(target);

        // The exact `<old_mem>--<old_slug>` spelling first: inside a
        // hierarchical mem the resolver strips that self-prefix and reads
        // the link as the same-mem slug (a cross-mem writer never gets it
        // past the gate), so it names the renamed entity although the
        // generic splitter refuses a `/` in the dash form as ambiguous.
        let self_prefixed = target
            .strip_prefix(old_mem)
            .and_then(|rest| rest.strip_prefix("--"))
            .is_some_and(|slug| slug == old_slug);
        let rewritten_inner = if self_prefixed {
            Some(format!("{pre}{old_mem}--{new_slug}{post}"))
        } else {
            match split_cross_mem_target(target) {
                Some((mem, sep, slug)) if mem == old_mem && slug == old_slug => {
                    Some(format!("{pre}{old_mem}{sep}{new_slug}{post}"))
                }
                _ => None,
            }
        };

        if let Some(new_target) = rewritten_inner {
            out.push_str("[[");
            out.push_str(&new_target);
            if let Some(lbl) = label {
                out.push('|');
                out.push_str(lbl);
            }
            out.push_str("]]");
            rewritten += 1;
        } else {
            out.push_str(&text[whole.start()..whole.end()]);
        }
        last_end = whole.end();
    }
    out.push_str(&text[last_end..]);
    (out, rewritten)
}

/// Rewrite every cross-mem wiki-link in `text` whose mem half matches
/// `old_mem` — regardless of slug — to carry `new_mem` instead,
/// preserving the separator (`:` or `--`), the slug, and any `|label`
/// suffix. The mem-rename counterpart of [`rewrite_cross_mem_slug`]:
/// that function retargets one renamed entity, this one retargets a
/// whole renamed mem.
///
/// Matches inside code blocks and inline code spans are not
/// rewritten (same discipline as the two sibling rewriters). Returns
/// the rewritten text plus a count of how many matches were changed.
///
/// Unlike its siblings this one takes a **whole entity file** — the
/// mem sweep rewrites files in place — so it masks via
/// [`mask_file_for_link_scan`].
pub(crate) fn rewrite_mem_prefix(text: &str, old_mem: &str, new_mem: &str) -> (String, usize) {
    rewrite_mem_prefix_masked(text, old_mem, new_mem, &mask_file_for_link_scan(text))
}

/// [`rewrite_mem_prefix`] with the mask supplied, so a caller that holds a
/// SECTION body rather than a whole file can pass the section-safe mask. The
/// two masks differ in one way that matters here: the file form trims a
/// leading `---…---` block as frontmatter and leaves it unmasked, which a
/// section body must never have done to it, because a section may legitimately
/// open with a `---` thematic break.
fn rewrite_mem_prefix_masked(
    text: &str,
    old_mem: &str,
    new_mem: &str,
    masked: &str,
) -> (String, usize) {
    let link_re = Regex::new(r"\[\[([^\]]*)\]\]").unwrap();
    let mut out = String::with_capacity(text.len());
    let mut last_end = 0usize;
    let mut rewritten = 0usize;

    for cap in link_re.captures_iter(masked) {
        let whole = cap.get(0).unwrap();
        let inner = cap.get(1).unwrap();
        let inner_str = &text[inner.start()..inner.end()];
        let (target, label) = match inner_str.find('|') {
            Some(i) => (&inner_str[..i], Some(&inner_str[i + 1..])),
            None => (inner_str, None),
        };

        out.push_str(&text[last_end..whole.start()]);

        // Exact-prefix match on the qualifier rather than the grammar
        // splitter: the splitter refuses a `/` in the mem half (that is
        // the decoder's ambiguity rule), but the caller names the mem
        // outright, and a hierarchical mem's own links (`[[a/b--slug]]`,
        // `[[a/b:slug]]`) are exactly what an export to its leaf name
        // has to retarget.
        let rewritten_inner = split_qualified_target(target, old_mem)
            .map(|(sep, slug)| format!("{new_mem}{sep}{slug}"));

        if let Some(new_target) = rewritten_inner {
            out.push_str("[[");
            out.push_str(&new_target);
            if let Some(lbl) = label {
                out.push('|');
                out.push_str(lbl);
            }
            out.push_str("]]");
            rewritten += 1;
        } else {
            out.push_str(&text[whole.start()..whole.end()]);
        }
        last_end = whole.end();
    }
    out.push_str(&text[last_end..]);
    (out, rewritten)
}
/// [`rewrite_mem_prefix`] for a SECTION body rather than a whole file.
///
/// The difference is the mask: the file form trims a leading `---…---` block
/// as frontmatter and leaves it unmasked, which a section body must never
/// have done to it, because a section may legitimately open with a `---`
/// thematic break. Called where a mark's own bytes are rewritten, so the
/// section-level pass and the file-level pass cannot disagree about what was
/// masked and leave a mark hashing bytes the file does not hold.
pub(crate) fn rewrite_mem_prefix_in_section(
    body: &str,
    old_mem: &str,
    new_mem: &str,
) -> (String, usize) {
    rewrite_mem_prefix_masked(body, old_mem, new_mem, &mask_for_link_scan(body))
}

/// Split a target that names `mem` outright as its qualifier into
/// `(separator, slug)`: `<mem>:<slug>` or `<mem>--<slug>`, the slug
/// non-empty and the `::` reserved syntax left alone. `None` for a bare
/// slug or a target qualified by another mem. Unlike
/// [`split_cross_mem_target`] the mem may carry `/`: the caller knows
/// which mem it means, so no grammar decision is taken here.
fn split_qualified_target<'a>(target: &'a str, mem: &str) -> Option<(&'static str, &'a str)> {
    let rest = target.strip_prefix(mem)?;
    if let Some(slug) = rest.strip_prefix(':') {
        if !slug.is_empty() && !slug.starts_with(':') {
            return Some((":", slug));
        }
        return None;
    }
    let slug = rest.strip_prefix("--")?;
    (!slug.is_empty()).then_some(("--", slug))
}

/// Decompose a cross-mem wiki-link target half into
/// `(mem, separator, slug)`. Returns `None` for bare-slug forms.
///
/// Recognised separators (in order): `:` (preferred Tier-2 form),
/// `--` (the EntityId's own format, ambiguous with same-mem slugs
/// containing dashes — disambiguation is the caller's concern). The
/// `:` form wins when both could match because the parser canonicalises
/// new cross-mem wiki-links to `:`.
///
/// The mem half follows the resolver's tiers: the colon form takes a
/// hierarchical mem (`[[team/sub:slug]]` is the only unambiguous
/// spelling of a reference into `team/sub`, and the parser accepts
/// it), the dash form stays flat-only because `team/sub--slug` is the
/// ambiguous shape the resolver refuses. A colon target into a
/// hierarchical mem used to fall out here as `None`, so a rename found
/// the referrer (the lenient parser resolves it) and then left its
/// body untouched while rewriting its relationship row.
fn split_cross_mem_target(target: &str) -> Option<(&str, &'static str, &str)> {
    if target.contains("::") {
        // `::` is reserved syntax in the parser — don't split.
        return None;
    }
    if let Some(idx) = target.find(':') {
        let (mem, rest) = target.split_at(idx);
        let slug = &rest[1..];
        if !mem.is_empty() && !slug.is_empty() {
            return Some((mem, ":", slug));
        }
    }
    if let Some(idx) = target.find("--") {
        let (mem, rest) = target.split_at(idx);
        let slug = &rest[2..];
        if !mem.is_empty() && !slug.is_empty() && !mem.contains('/') {
            return Some((mem, "--", slug));
        }
    }
    None
}

/// A link target split the way the decoder reads it: the leading `../`
/// segments, the id the link names, and what follows it (a `.md` suffix
/// and a `#anchor`), so a rewrite can change the id and keep the rest.
/// Mirrors `entity::id::strip_wiki_link_decorations`, which cuts the
/// anchor first, then the `../` prefix, then the `.md` suffix.
fn split_link_decorations(target: &str) -> (&str, &str, &str) {
    let anchor_at = target.find('#').unwrap_or(target.len());
    let body = &target[..anchor_at];
    let pre_len = body.len() - body.trim_start_matches("../").len();
    let core_md = &body[pre_len..];
    let core_len = core_md.strip_suffix(".md").map_or(core_md.len(), str::len);
    (
        &target[..pre_len],
        &target[pre_len..pre_len + core_len],
        &target[pre_len + core_len..],
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A hierarchical mem's own qualified links follow the mem to a new
    /// name in both forms; a target qualified by a longer path that
    /// merely starts with the mem, a bare slug, and code spans stay.
    #[test]
    fn rewrites_hierarchical_mem_prefix_in_both_forms() {
        let text = "\
---
type: note
---
# N

See [[planning/plan-x--alpha]] and [[planning/plan-x:beta|the beta]], not
[[planning/plan-xy--gamma]] nor [[alpha]] nor `[[planning/plan-x--code]]`.
";
        let (out, n) = rewrite_mem_prefix(text, "planning/plan-x", "plan-x");
        assert_eq!(n, 2);
        assert!(out.contains("[[plan-x--alpha]]"), "{out}");
        assert!(out.contains("[[plan-x:beta|the beta]]"), "{out}");
        assert!(out.contains("[[planning/plan-xy--gamma]]"), "{out}");
        assert!(out.contains("[[alpha]]"), "{out}");
        assert!(out.contains("`[[planning/plan-x--code]]`"), "{out}");
    }

    #[test]
    fn rewrites_bare_self_reference() {
        let (out, n) = rewrite_bare_slug("see [[old-slug]] for context", "old-slug", "new-slug");
        assert_eq!(out, "see [[new-slug]] for context");
        assert_eq!(n, 1);
    }

    #[test]
    fn preserves_label_on_rewrite() {
        let (out, n) = rewrite_bare_slug("[[old-slug|the link]]", "old-slug", "new-slug");
        assert_eq!(out, "[[new-slug|the link]]");
        assert_eq!(n, 1);
    }

    #[test]
    fn leaves_unrelated_links_alone() {
        let (out, n) = rewrite_bare_slug(
            "[[other]] then [[old-slug]] then [[third]]",
            "old-slug",
            "new-slug",
        );
        assert_eq!(out, "[[other]] then [[new-slug]] then [[third]]");
        assert_eq!(n, 1);
    }

    #[test]
    fn skips_matches_inside_fenced_code_block() {
        let input = "before [[old-slug]]\n```\ncode [[old-slug]]\n```\nafter [[old-slug]]";
        let (out, n) = rewrite_bare_slug(input, "old-slug", "new-slug");
        assert!(out.contains("```\ncode [[old-slug]]\n```"));
        assert!(out.starts_with("before [[new-slug]]"));
        assert!(out.ends_with("after [[new-slug]]"));
        assert_eq!(n, 2);
    }

    #[test]
    fn skips_matches_inside_inline_code() {
        let input = "prose [[old-slug]] then `code [[old-slug]] here` again [[old-slug]]";
        let (out, n) = rewrite_bare_slug(input, "old-slug", "new-slug");
        assert!(out.contains("`code [[old-slug]] here`"));
        assert_eq!(
            out,
            "prose [[new-slug]] then `code [[old-slug]] here` again [[new-slug]]"
        );
        assert_eq!(n, 2);
    }

    #[test]
    fn cross_mem_form_is_not_rewritten_by_bare_slug_pass() {
        let (out, n) = rewrite_bare_slug(
            "[[specs:old-slug]] and [[old-slug]]",
            "old-slug",
            "new-slug",
        );
        assert_eq!(out, "[[specs:old-slug]] and [[new-slug]]");
        assert_eq!(n, 1);
    }

    #[test]
    fn returns_zero_count_when_nothing_matches() {
        let (out, n) = rewrite_bare_slug("no links here", "old-slug", "new-slug");
        assert_eq!(out, "no links here");
        assert_eq!(n, 0);
    }

    #[test]
    fn cross_mem_rewrites_colon_form() {
        let (out, n) = rewrite_cross_mem_slug(
            "see [[specs:old-name]] now",
            "specs",
            "old-name",
            "new-name",
        );
        assert_eq!(out, "see [[specs:new-name]] now");
        assert_eq!(n, 1);
    }

    /// A hierarchical mem is addressed in the colon form, and inside
    /// the mem itself also by the exact `<mem>--<slug>` spelling (the
    /// resolver strips that self-prefix); the rewriter follows both. A
    /// dash form into a DIFFERENT hierarchical mem stays out: it is the
    /// ambiguous shape the resolver refuses, so it never names a
    /// referrer.
    #[test]
    fn cross_mem_rewrites_colon_form_into_a_hierarchical_mem() {
        let (out, n) = rewrite_cross_mem_slug(
            "see [[library/a:old-name|the card]], [[library/a--old-name]] and [[library/b--old-name]]",
            "library/a",
            "old-name",
            "new-name",
        );
        assert_eq!(
            out,
            "see [[library/a:new-name|the card]], [[library/a--new-name]] and [[library/b--old-name]]"
        );
        assert_eq!(n, 2);
    }

    #[test]
    fn cross_mem_rewrites_double_hyphen_form() {
        let (out, n) =
            rewrite_cross_mem_slug("see [[specs--old-name]]", "specs", "old-name", "new-name");
        assert_eq!(out, "see [[specs--new-name]]");
        assert_eq!(n, 1);
    }

    #[test]
    fn cross_mem_preserves_label() {
        let (out, n) = rewrite_cross_mem_slug(
            "[[specs:old-name|the spec]]",
            "specs",
            "old-name",
            "new-name",
        );
        assert_eq!(out, "[[specs:new-name|the spec]]");
        assert_eq!(n, 1);
    }

    #[test]
    fn cross_mem_skips_other_mems_and_other_slugs() {
        let (out, n) = rewrite_cross_mem_slug(
            "[[memos:old-name]] [[specs:other]] [[specs:old-name]]",
            "specs",
            "old-name",
            "new-name",
        );
        assert_eq!(out, "[[memos:old-name]] [[specs:other]] [[specs:new-name]]");
        assert_eq!(n, 1);
    }

    #[test]
    fn cross_mem_skips_bare_slug() {
        let (out, n) = rewrite_cross_mem_slug(
            "[[old-name]] [[specs:old-name]]",
            "specs",
            "old-name",
            "new-name",
        );
        assert_eq!(out, "[[old-name]] [[specs:new-name]]");
        assert_eq!(n, 1);
    }

    /// The mem sweep hands this rewriter a WHOLE entity file. Masking
    /// the file rather than its body let a YAML value that reads as a
    /// fence opener blank the body, so the scan found no links, the
    /// rewrite reported zero changes, and a mem rename left dangling
    /// cross-mem references behind — silently, since zero changes is
    /// indistinguishable from nothing to change.
    #[test]
    fn mem_prefix_rewrite_survives_fence_shaped_frontmatter() {
        let file = "---\ntype: spec\nnotes: |\n   ```\n   sample\n---\n\n# T\n\n## Identity\n\nSee [[old:target]].\n";
        let (out, count) = rewrite_mem_prefix(file, "old", "new");
        assert_eq!(count, 1, "the link must be found and rewritten: {out}");
        assert!(out.contains("[[new:target]]"), "{out}");
        assert!(
            out.contains("notes: |"),
            "frontmatter must survive verbatim: {out}"
        );
    }

    /// Complement: a link inside a real code block in the body is
    /// still left alone, whole-file input notwithstanding.
    #[test]
    fn mem_prefix_rewrite_still_skips_body_code_blocks() {
        let file = "---\ntype: spec\n---\n\n# T\n\n## Identity\n\n```\n[[old:target]]\n```\n\nAnd [[old:other]].\n";
        let (out, count) = rewrite_mem_prefix(file, "old", "new");
        assert_eq!(count, 1, "only the prose link may be rewritten: {out}");
        assert!(out.contains("```\n[[old:target]]\n```"), "{out}");
        assert!(out.contains("[[new:other]]"), "{out}");
    }

    #[test]
    fn cross_mem_skips_inside_code_block() {
        let input = "[[specs:old-name]]\n```\n[[specs:old-name]]\n```\n[[specs:old-name]]";
        let (out, n) = rewrite_cross_mem_slug(input, "specs", "old-name", "new-name");
        assert!(out.contains("```\n[[specs:old-name]]\n```"));
        assert_eq!(n, 2);
    }

    /// A section body may open with a `---` thematic break, and the SECTION
    /// form must not mistake that for frontmatter and leave the region
    /// unmasked. The file form does trim it, which is right for a file and
    /// wrong for a body: used on a section it rewrites a link inside a fence
    /// the file-level pass masked, and a mark then hashes bytes the file does
    /// not hold.
    #[test]
    fn the_section_form_masks_a_body_that_opens_with_a_thematic_break() {
        // The fence sits INSIDE what the file form mistakes for frontmatter,
        // which is the region it leaves unmasked.
        let body = "---\n\n```\n[[old:slug]]\n```\n\n---\n\nA break, not frontmatter.\n";
        let (file_form, file_count) = rewrite_mem_prefix(body, "old", "new");
        let (section_form, section_count) = rewrite_mem_prefix_in_section(body, "old", "new");
        assert_eq!(
            section_count, 0,
            "the fenced link is masked for a section body: {section_form}"
        );
        assert_eq!(section_form, body, "so the body comes back untouched");
        assert!(
            file_count > 0,
            "while the file form takes the leading block for frontmatter and rewrites it, \
             which is the divergence this exists to avoid: {file_form}"
        );
    }
}