memstead-base 0.11.0

Engine internals for Memstead — store, parser, validators, filesystem-mem engine. Internal library surface consumed by the memstead binaries — pre-1.0, experimental, 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
//! 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()]);
        if target == old_slug {
            out.push_str("[[");
            out.push_str(new_slug);
            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()]);

        let rewritten_inner = match split_cross_mem_target(target) {
            Some((mem, sep, slug)) if mem == old_mem && slug == old_slug => {
                Some(format!("{old_mem}{sep}{new_slug}"))
            }
            _ => 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) {
    let masked = mask_file_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()]);

        let rewritten_inner = match split_cross_mem_target(target) {
            Some((mem, sep, slug)) if mem == old_mem => Some(format!("{new_mem}{sep}{slug}")),
            _ => 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)
}

/// 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 `:`.
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() && !mem.contains('/') {
            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
}

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

    #[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);
    }

    #[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);
    }
}