Skip to main content

memstead_base/entity/
id.rs

1//! Entity ID parsing, generation, and path mapping.
2
3use super::EntityId;
4use unicode_normalization::UnicodeNormalization;
5
6/// Cap on the full `mem--slug` entity id (Unicode scalar length).
7/// 200 leaves headroom for `mem--`-style prefixes and the `.md`
8/// suffix against the 255-byte `NAME_MAX` ceiling on common
9/// filesystems. The read-path validator on the MCP surface and the
10/// write-path slug derivation share this constant so an entity that
11/// the write side accepts is always readable on the same wire.
12/// F2 + F4.
13pub const ENTITY_ID_MAX_LEN: usize = 200;
14
15/// Error cases for title→slug derivation. `title_to_slug` itself is
16/// total — any title produces a slug (residual cases like
17/// all-emoji collapse to a deterministic short-hash id) — so it never
18/// returns these variants directly. The strict mutation-entry gate
19/// [`validate_and_derive_slug`] returns them for control characters
20/// and for input that would have fallen back to the hash slug;
21/// [`enforce_id_length`] returns [`Self::IdTooLong`] when the
22/// derived `mem--slug` exceeds the read-path length cap.
23///
24/// Loader and parse paths continue to call [`title_to_slug`] so
25/// pre-gate entities created with the old permissive pipeline remain
26/// readable.
27#[derive(Debug, thiserror::Error)]
28pub enum SlugError {
29    /// The derived `mem--slug` id exceeds [`ENTITY_ID_MAX_LEN`]. The
30    /// read-path validator rejects ids past this length, so without
31    /// this guard a title that the write path accepts produces an
32    /// entity that is silently unreachable on read.
33    ///
34    /// The bound is on the **composed id** (`<mem>--<slug>`), which is
35    /// also the on-disk filename — so the budget is mem-name-dependent
36    /// and the same title can be valid in a short-named mem and rejected
37    /// in a longer-named one. `input` echoes that composed id (not the
38    /// title) so it agrees with `length`: the payload measures one
39    /// quantity, the id, end to end. `max` is [`ENTITY_ID_MAX_LEN`] so the
40    /// agent can shorten by the exact delta. F2 + F4.
41    #[error(
42        "entity id \"{input}\" is {length} characters (max {max}); the id is `<mem>--<slug>`, so the title budget shrinks as the mem name grows — shorten the title"
43    )]
44    IdTooLong {
45        /// The composed `<mem>--<slug>` id whose length exceeded the
46        /// cap. Echoed as the `input` wire field so `input` and `length`
47        /// describe the same measured quantity.
48        input: String,
49        length: usize,
50        max: usize,
51    },
52    /// Strict mutation-entry rejection: the title is empty,
53    /// whitespace-only, or composed exclusively of pipeline-separator
54    /// characters (hyphens) so the slug pipeline would have collapsed
55    /// it to a hash-fallback id. Recovery: supply a non-empty title
56    /// with at least one alphanumeric character. F4.
57    #[error("title is empty or contains no slug-meaningful characters")]
58    TitleEmpty { input: String },
59    /// Strict mutation-entry rejection: the title contains control
60    /// characters (newline, tab, other C0/C1 controls). These are
61    /// Unicode whitespace, so the slug pipeline silently folds them to
62    /// hyphens and accepts the title — but they survive verbatim into the
63    /// stored `# H1` heading, which then splits across lines so every
64    /// read truncates the title at the first control char (search and
65    /// `memstead_entity` see only the prefix). Refused up front with the same
66    /// named-offenders + `proposed_slug` recovery shape the invalid-char
67    /// guard uses. `control_chars` lists each distinct offender in source
68    /// order; `proposed_slug` is the slug the pipeline would produce, for
69    /// a mechanical retry with a single-line title. F8.
70    #[error(
71        "title {input:?} contains control character(s) {control_chars:?} that would split the stored heading — \
72         retry with a single-line title (proposed slug: \"{proposed_slug}\")"
73    )]
74    TitleHasControlChars {
75        input: String,
76        control_chars: Vec<char>,
77        proposed_slug: String,
78    },
79}
80
81impl SlugError {
82    /// Stable discriminator for the structured-details `reason` field
83    /// on the `INVALID_TITLE` wire envelope. Each surface (MCP, CLI)
84    /// reads this when building the response payload.
85    pub fn reason(&self) -> &'static str {
86        match self {
87            SlugError::IdTooLong { .. } => "id_too_long",
88            SlugError::TitleEmpty { .. } => "empty",
89            SlugError::TitleHasControlChars { .. } => "control_chars",
90        }
91    }
92}
93
94/// The separator between mem and entity path in IDs.
95/// Build an EntityId from mem and title.
96pub fn build_id(mem: &str, title: &str) -> Result<EntityId, SlugError> {
97    let slug = title_to_slug(title)?;
98    let id = EntityId::new(mem, &slug);
99    enforce_id_length(id.as_ref())?;
100    Ok(id)
101}
102
103/// Reject ids whose Unicode scalar length exceeds
104/// [`ENTITY_ID_MAX_LEN`]. Shared by [`build_id`] and the engine's
105/// `create_entity` / `rename_entity` paths so the write side never
106/// produces an id the read side would refuse. The cap is on the
107/// composed `<mem>--<slug>` id (which is also the filename), so the
108/// error echoes the id itself — the `reason`, the echoed `input`, and
109/// the reported `length` all describe the id, not the title. F2 + F4.
110pub fn enforce_id_length(id: &str) -> Result<(), SlugError> {
111    if id.chars().count() > ENTITY_ID_MAX_LEN {
112        return Err(SlugError::IdTooLong {
113            input: id.to_string(),
114            length: id.chars().count(),
115            max: ENTITY_ID_MAX_LEN,
116        });
117    }
118    Ok(())
119}
120
121/// Convert a title string to a kebab-case slug.
122///
123/// Pipeline (F1, option B+A):
124///
125/// 1. **NFC-normalize** so combining sequences fold into precomposed
126///    forms (`Café` written NFD becomes `Café` written NFC). One
127///    canonical surface form keeps slug equality byte-stable across
128///    NFD-storing filesystems (older HFS+) and NFC-default ones
129///    (APFS, ext4, NTFS).
130/// 2. **Lowercase** via Unicode default case-folding — correct for
131///    Latin / Cyrillic / Greek / Armenian; no-op for case-less
132///    scripts (CJK, Arabic, Hebrew, Devanagari, Thai, etc.).
133/// 3. **Whitespace → hyphen**.
134/// 4. **Filter to `is_alphanumeric() || '-'`** — Unicode alphanumeric,
135///    not ASCII. Keeps every Latin and non-Latin letter or digit;
136///    drops combining marks, punctuation, symbols, emoji, and the
137///    reserved `--` / `:` separators by construction.
138/// 5. **Collapse hyphen runs, trim**.
139///
140/// Always returns `Ok(...)`. When the filter leaves the slug empty
141/// (all-emoji titles, all-punctuation, all-symbol titles), the slug
142/// degrades to a deterministic short hash of the title
143/// (`entity-<8-hex>`) rather than failing. Titles that are already
144/// slug-form — case-less scripts (`知識グラフ`) and lowercase
145/// single-token Latin (`wohnung`) — produce slug == title, so
146/// Obsidian-style `[[<title>]]` authoring round-trips without lookup
147/// for exactly those titles; any other title (a capital, a space:
148/// `Knowledge Graph`) derives a different slug, and the strict
149/// wiki-link decoder below refuses the natural form as a link target
150/// — such entities are linked by slug (`[[knowledge-graph]]`).
151pub fn title_to_slug(title: &str) -> Result<String, SlugError> {
152    let normalized: String = title.nfc().collect();
153    let slug: String = normalized
154        .chars()
155        .flat_map(|c| c.to_lowercase())
156        .map(|c| if c.is_whitespace() { '-' } else { c })
157        .filter(|c| c.is_alphanumeric() || *c == '-')
158        .collect::<String>()
159        .split('-')
160        .filter(|s| !s.is_empty())
161        .collect::<Vec<_>>()
162        .join("-");
163    if slug.is_empty() {
164        return Ok(format!("entity-{}", short_hash(title)));
165    }
166    Ok(slug)
167}
168
169/// The accepted title grammar, stated as a rule. THE single sentence
170/// every surface that documents titles carries: the CLI's
171/// create/rename help embeds it at build time, the MCP
172/// `memstead_create` / `memstead_rename` descriptions contain it
173/// verbatim (a tool-surface test asserts the containment), and the
174/// handbook quotes it naming this constant as its source. A
175/// conformance test in this module asserts
176/// [`validate_and_derive_slug`]'s behaviour matches the sentence's
177/// claim — so neither the prose nor the validator can drift alone.
178///
179/// The sentence's two claims, executable:
180///
181/// ```
182/// use memstead_base::entity::id::validate_and_derive_slug;
183///
184/// // "control characters such as tab/newline are rejected"
185/// assert!(validate_and_derive_slug("two\nlines").is_err());
186///
187/// // "characters outside Unicode alphanumerics, whitespace, and
188/// // hyphen are dropped from the derived slug" — and reported.
189/// let d = validate_and_derive_slug("The Gate's Rule — v2").unwrap();
190/// assert_eq!(d.slug, "the-gates-rule-v2");
191/// assert_eq!(d.dropped_chars, vec!['\'', '—']);
192/// ```
193pub const TITLE_GRAMMAR_RULE: &str = "Titles accept any single-line text (control characters such as tab/newline are rejected); the title is stored verbatim as display text, while characters outside Unicode alphanumerics, whitespace, and hyphen are dropped from the derived slug — warning TITLE_CHARS_DROPPED_FROM_SLUG names them";
194
195/// A strict-gate derivation result: the slug plus the distinct title
196/// characters (source order, post NFC + case-fold) the pipeline
197/// dropped on the way. `dropped_chars` non-empty means the title and
198/// its id diverge beyond case/whitespace — the mutation surfaces it
199/// as the typed `TITLE_CHARS_DROPPED_FROM_SLUG` warning so the
200/// divergence stays visible without being fatal.
201#[derive(Debug, Clone, PartialEq, Eq)]
202pub struct SlugDerivation {
203    pub slug: String,
204    pub dropped_chars: Vec<char>,
205}
206
207/// Strict slug derivation for mutation entry (`memstead_create`,
208/// `memstead_rename`). Runs the same pipeline as [`title_to_slug`] —
209/// byte-identical slugs for every title — but refuses the residual
210/// cases the permissive variant tolerates:
211///
212/// 1. **Control characters.** They would survive verbatim into the
213///    stored `# H1` and split it across lines. Returns
214///    [`SlugError::TitleHasControlChars`].
215/// 2. **Empty / collapses-to-empty.** Empty input, whitespace-only,
216///    hyphen-only, or all-dropped input — anything that would force
217///    the loader-path hash fallback. Returns [`SlugError::TitleEmpty`].
218///
219/// Any other character is admitted: the title is display text, stored
220/// verbatim, and characters outside the slug alphabet are dropped from
221/// the derived slug and reported in
222/// [`SlugDerivation::dropped_chars`] ([`TITLE_GRAMMAR_RULE`]).
223///
224/// Loader paths continue to call [`title_to_slug`] so pre-gate
225/// entities created with the old permissive pipeline remain
226/// readable — only mutation entry runs this strict gate.
227///
228/// ```
229/// use memstead_base::entity::id::{SlugError, validate_and_derive_slug};
230///
231/// // The happy path: Unicode-aware kebab-case, divergence reported.
232/// let d = validate_and_derive_slug("Knowledge Graph!").unwrap();
233/// assert_eq!(d.slug, "knowledge-graph");
234/// assert_eq!(d.dropped_chars, vec!['!']);
235///
236/// // Refusal 1: control characters.
237/// assert!(matches!(
238///     validate_and_derive_slug("tab\there"),
239///     Err(SlugError::TitleHasControlChars { .. })
240/// ));
241///
242/// // Refusal 2: a title whose slug collapses to empty.
243/// assert!(matches!(
244///     validate_and_derive_slug("!!!"),
245///     Err(SlugError::TitleEmpty { .. })
246/// ));
247/// ```
248pub fn validate_and_derive_slug(title: &str) -> Result<SlugDerivation, SlugError> {
249    let normalized: String = title.nfc().collect();
250    let case_folded: String = normalized.chars().flat_map(|c| c.to_lowercase()).collect();
251
252    // Control characters (newline, tab, other C0/C1) are Unicode
253    // whitespace, so the slug pipeline below would fold them to hyphens
254    // and accept the title — but they survive into the stored `# H1`,
255    // splitting it across lines and truncating every read of the title.
256    // Refuse them before the slug derivation.
257    let mut control_chars: Vec<char> = Vec::new();
258    for c in case_folded.chars() {
259        if c.is_control() && !control_chars.contains(&c) {
260            control_chars.push(c);
261        }
262    }
263    if !control_chars.is_empty() {
264        let proposed = title_to_slug(title).unwrap_or_default();
265        return Err(SlugError::TitleHasControlChars {
266            input: title.to_string(),
267            control_chars,
268            proposed_slug: proposed,
269        });
270    }
271
272    // Characters outside the slug alphabet are dropped from the id —
273    // recorded, not refused: the title is display text, the slug is
274    // the sanitised identifier, and the divergence rides back to the
275    // caller as a typed warning.
276    let mut dropped_chars: Vec<char> = Vec::new();
277    for c in case_folded.chars() {
278        if c.is_whitespace() || c == '-' || c.is_alphanumeric() {
279            continue;
280        }
281        if !dropped_chars.contains(&c) {
282            dropped_chars.push(c);
283        }
284    }
285
286    let slug: String = case_folded
287        .chars()
288        .filter(|c| c.is_whitespace() || *c == '-' || c.is_alphanumeric())
289        .map(|c| if c.is_whitespace() { '-' } else { c })
290        .collect::<String>()
291        .split('-')
292        .filter(|s| !s.is_empty())
293        .collect::<Vec<_>>()
294        .join("-");
295
296    if slug.is_empty() {
297        return Err(SlugError::TitleEmpty {
298            input: title.to_string(),
299        });
300    }
301
302    Ok(SlugDerivation {
303        slug,
304        dropped_chars,
305    })
306}
307
308/// Deterministic 8-char hex digest used as the fallback slug when
309/// the title contains no Unicode alphanumeric characters (the
310/// residual case of [`title_to_slug`]'s pipeline). 32 bits is
311/// plenty for collision-resistance inside a single mem; the
312/// fallback only fires for titles that contain no
313/// agent-meaningful characters anyway, so the opaque form is
314/// acceptable. F1 (option A backstop).
315fn short_hash(input: &str) -> String {
316    use sha2::{Digest, Sha256};
317    let digest = Sha256::digest(input.as_bytes());
318    format!(
319        "{:02x}{:02x}{:02x}{:02x}",
320        digest[0], digest[1], digest[2], digest[3]
321    )
322}
323
324/// Convert a relative file path to a mem-prefixed entity ID.
325///
326/// `file_path_to_id("architecture/result.md", "specs")` → `specs--architecture/result`
327pub fn file_path_to_id(path: &str, mem: &str) -> EntityId {
328    let stripped = path.strip_suffix(".md").unwrap_or(path);
329    EntityId::new(mem, stripped)
330}
331
332/// Strict wiki-link grammar refusal. Returned by [`wiki_link_to_id`]
333/// when the input between `[[...]]` (after alias / `.md` strip) does
334/// not resolve to a slug-form `EntityId`. Two variants matching the
335/// two grammars a wiki-link target carries:
336///
337/// - [`Self::InvalidMemName`] — Tier-2 prefix `[[mem:slug]]`'s
338///   mem name fails [`validate_mem_name_grammar`]. Recovery is
339///   manual: mem names are fixed identifiers in the workspace, not
340///   free-form text the agent can slugify.
341/// - [`Self::InvalidTarget`] — the slug-form path fails
342///   [`validate_id_path_grammar`]. Carries the
343///   [`title_to_slug`]-derived suggestion (omitted when the input
344///   has no meaningful slug equivalent — empty, all-punctuation,
345///   all-emoji).
346#[derive(Debug, thiserror::Error, Clone)]
347pub enum WikiLinkError {
348    #[error("mem prefix '{raw}' is not a valid mem name: {reason}")]
349    InvalidMemName { raw: String, reason: String },
350    #[error("wiki-link target '{raw}' is not slug-form: {reason}")]
351    InvalidTarget {
352        raw: String,
353        suggested: Option<String>,
354        reason: String,
355    },
356}
357
358/// Compute the [`title_to_slug`]-derived suggestion for a malformed
359/// wiki-link target. Returns `None` when the slug pipeline produces
360/// either an empty result or the deterministic hash fallback
361/// (`entity-<8hex>`) — both signal that the input has no canonical
362/// form the agent can mechanically lift into a retry.
363fn wiki_link_suggestion(raw: &str) -> Option<String> {
364    let derived = title_to_slug(raw).ok()?;
365    if derived.is_empty() || derived.starts_with("entity-") {
366        return None;
367    }
368    validate_id_path_grammar(&derived)
369        .is_ok()
370        .then_some(derived)
371}
372
373/// Convert a wiki-link target to a mem-prefixed entity ID, refusing
374/// non-slug-form inputs.
375///
376/// Recognises three grammars:
377/// - **Tier 0** `[[<mem>--<slug>]]` — cross-mem dash-form,
378///   symmetric with every engine-emitted ID: body wiki-links accept
379///   the canonical `<mem>--<slug>` form the engine writes elsewhere
380///   so an agent can author the same grammar in both directions.
381///   `<mem>` must match the single-segment mem-name grammar
382///   (`[a-z0-9-]+`, no `/`); hierarchical mem names stay on the
383///   Tier-2 colon-form. Cross-mem routing is policy-gated downstream in
384///   the alias-synthesis pass (same code path that already gates
385///   body-link → REFERENCES emission).
386/// - **Tier 1** `[[slug]]` or `[[a/b/c]]` — same-mem, resolves to
387///   `<current_mem>--<slug>`.
388/// - **Tier 2** `[[leaf:slug]]` — cross-mem, same mem-repo, resolves
389///   to `<leaf>--<slug>`. Hierarchical paths are first-class: the
390///   prefix accepts the full `team/sub-mem` form, so
391///   `[[team/sub-mem:auth-service]]` resolves to
392///   `team/sub-mem--auth-service`. Tier-1 with a
393///   hierarchical-mem dash-prefix (`[[team/sub-mem--auth-service]]`)
394///   remains unsupported — that combination is genuinely ambiguous
395///   between a cross-mem reference into a hierarchical mem and a
396///   same-mem entity at a hierarchical slug. Operators authoring
397///   such references must use the colon Tier-2 form.
398///
399/// Strips `[[` / `]]`, Obsidian alias (`|display`), `../` prefixes, `.md`
400/// suffix, and a redundant leading `<current_mem>--` (so an agent that
401/// writes the canonical fully-qualified id `[[mem--slug]]` produces the
402/// same `EntityId` as the bare-slug form `[[slug]]` instead of doubly-
403/// prefixing into `mem--mem--slug`).
404///
405/// Strictness: any input whose Tier-2 prefix fails
406/// [`validate_mem_name_grammar`] or whose resolved slug fails
407/// [`validate_id_path_grammar`] refuses with [`WikiLinkError`]. There is
408/// no permissive form that constructs an `EntityId` from any character
409/// sequence between the brackets — callers
410/// (`extract_inline_links`, the relate path's body scanners)
411/// propagate the refusal so an agent's `[[Knowledge Graph]]` body
412/// link can no longer land a malformed auto-stub. Read-side scanners
413/// that must tolerate pre-strict on-disk drift use
414/// [`wiki_link_to_id_lenient`].
415///
416/// Hierarchical-dash ambiguity: the Tier-1 fallback refuses inputs whose post-
417/// self-prefix-strip slug contains BOTH `/` and `--`
418/// (`[[team/sub-mem--target]]`). The combination is grammatically
419/// ambiguous between a cross-mem reference into a hierarchical mem
420/// and a same-mem entity at a hierarchical slug; the refusal carries
421/// the canonical colon form (`team/sub-mem:target`) as `suggested`.
422pub fn wiki_link_to_id(link: &str, current_mem: &str) -> Result<EntityId, WikiLinkError> {
423    let stripped = strip_wiki_link_decorations(link);
424
425    if !stripped.contains("::")
426        && let Some(colon_idx) = stripped.find(':')
427    {
428        let (prefix, rest) = stripped.split_at(colon_idx);
429        let slug_part = &rest[1..];
430        if !prefix.is_empty() && !slug_part.is_empty() {
431            if let Err(reason) = validate_mem_name_grammar(prefix) {
432                return Err(WikiLinkError::InvalidMemName {
433                    raw: prefix.to_string(),
434                    reason,
435                });
436            }
437            if let Err(reason) = validate_id_path_grammar(slug_part) {
438                let suggested = wiki_link_suggestion(slug_part).map(|s| format!("{prefix}:{s}"));
439                return Err(WikiLinkError::InvalidTarget {
440                    raw: stripped.to_string(),
441                    suggested,
442                    reason,
443                });
444            }
445            return Ok(EntityId::new(prefix, slug_part));
446        }
447    }
448
449    // Tier 0 — cross-mem dash form `<mem>--<slug>`. Symmetric
450    // with every engine-emitted ID. Recognises only
451    // single-segment mem names (no `/` in the prefix); the
452    // hierarchical-mem dash form is grammatically ambiguous (see
453    // the dash/slash refusal further down) and stays on the colon
454    // Tier-2 form. Routes to the named mem even when it differs
455    // from `current_mem` — the cross-mem policy gate fires in
456    // the alias-synthesis pass, not here.
457    if let Some(dash_idx) = stripped.find("--") {
458        let prefix = &stripped[..dash_idx];
459        let suffix = &stripped[dash_idx + 2..];
460        if !prefix.is_empty()
461            && !suffix.is_empty()
462            && !prefix.contains('/')
463            && validate_mem_name_grammar(prefix).is_ok()
464            && validate_id_path_grammar(suffix).is_ok()
465        {
466            return Ok(EntityId::new(prefix, suffix));
467        }
468    }
469
470    let slug = if !current_mem.is_empty() {
471        let self_prefix = format!("{current_mem}--");
472        stripped
473            .strip_prefix(self_prefix.as_str())
474            .unwrap_or(&stripped)
475    } else {
476        &stripped
477    };
478    // A slug carrying BOTH `/` and `--` is grammatically ambiguous —
479    // it could be a cross-mem reference into a hierarchical mem
480    // (`team/sub-mem--target` → mem `team/sub-mem`, slug `target`)
481    // or a same-mem entity at a hierarchical slug that happens to
482    // contain `--`. The docstring above pins the canonical disambiguation
483    // (colon-form for cross-mem) but the dash form silently collapsed
484    // to the same-mem interpretation pre-fix, landing phantom stubs
485    // for any agent writing `[[team/sub-mem--target]]` in body text.
486    // Refuse and surface the colon-form as the recovery hint.
487    if let Some(dash_idx) = slug.find("--")
488        && slug[..dash_idx].contains('/')
489    {
490        let prefix = &slug[..dash_idx];
491        let suffix = &slug[dash_idx + 2..];
492        let cross_mem_form = format!("{prefix}:{suffix}");
493        let same_mem_form = if current_mem.is_empty() {
494            format!("<current-mem>:{slug}")
495        } else {
496            format!("{current_mem}:{slug}")
497        };
498        return Err(WikiLinkError::InvalidTarget {
499            raw: stripped.to_string(),
500            suggested: Some(cross_mem_form),
501            reason: format!(
502                "wiki-link target contains both '/' and '--', which is ambiguous \
503                 between a cross-mem reference into a hierarchical mem and a \
504                 same-mem entity at a hierarchical slug; use the colon form \
505                 '[[{prefix}:{suffix}]]' for a cross-mem reference, or \
506                 '[[{same_mem_form}]]' for a same-mem entity whose slug \
507                 contains '--'"
508            ),
509        });
510    }
511    if let Err(reason) = validate_id_path_grammar(slug) {
512        return Err(WikiLinkError::InvalidTarget {
513            raw: stripped.to_string(),
514            suggested: wiki_link_suggestion(slug),
515            reason,
516        });
517    }
518    Ok(EntityId::new(current_mem, slug))
519}
520
521/// Permissive wiki-link decoder for read-side scanners that must
522/// tolerate pre-strict-gate on-disk drift (e.g. dangling-link
523/// reporters, body-link scanners on stored entities, archive readers
524/// for non-canonical sources). Returns an `EntityId` even for
525/// non-slug-form input — non-conformant chars flow through
526/// unchanged. Mutation paths MUST
527/// NOT use this helper; they use [`wiki_link_to_id`] and propagate
528/// the typed refusal.
529pub fn wiki_link_to_id_lenient(link: &str, current_mem: &str) -> EntityId {
530    let stripped = strip_wiki_link_decorations(link);
531
532    if !stripped.contains("::")
533        && let Some(colon_idx) = stripped.find(':')
534    {
535        let (prefix, rest) = stripped.split_at(colon_idx);
536        let slug_part = &rest[1..];
537        if !prefix.is_empty() && !slug_part.is_empty() {
538            return EntityId::new(prefix, slug_part);
539        }
540    }
541
542    // Tier 0 — cross-mem dash form. Read-side mirror of the strict
543    // decoder's recognition so dangling-link reports and graph
544    // inspectors interpret on-disk `[[other--target]]` the same way
545    // the mutation gate writes it. Pre-strict drift on older entities
546    // keeps the bare-slug fallback below for
547    // shapes the tier-0 doesn't admit (empty prefix, hierarchical
548    // prefix, malformed slug).
549    if let Some(dash_idx) = stripped.find("--") {
550        let prefix = &stripped[..dash_idx];
551        let suffix = &stripped[dash_idx + 2..];
552        if !prefix.is_empty()
553            && !suffix.is_empty()
554            && !prefix.contains('/')
555            && validate_mem_name_grammar(prefix).is_ok()
556            && validate_id_path_grammar(suffix).is_ok()
557        {
558            return EntityId::new(prefix, suffix);
559        }
560    }
561
562    let slug = if !current_mem.is_empty() {
563        let self_prefix = format!("{current_mem}--");
564        stripped
565            .strip_prefix(self_prefix.as_str())
566            .unwrap_or(&stripped)
567    } else {
568        &stripped
569    };
570    EntityId::new(current_mem, slug)
571}
572
573/// Strip `[[`/`]]`, the Obsidian alias suffix `|display`, the section
574/// anchor `#section` (plus any trailing `#sub` etc — stripped from the
575/// first `#` onward), leading `../` segments, and the trailing `.md`
576/// suffix from a raw wiki-link token. Shared by the strict and
577/// lenient decoders so the pre-grammar-gate textual normalisation is
578/// byte-equivalent on both paths.
579///
580/// `#anchor` strip: Obsidian-style section anchors are display-only at
581/// the graph layer; the engine has no semantic use for them. Strip
582/// from the first `#` onward so multi-anchor forms like
583/// `target#a#b` collapse to `target` in one pass. Ordered after the
584/// `|alias` strip so `target#section|display` correctly drops both
585/// (the alias strip drops `|display` first, leaving `target#section`;
586/// the anchor strip then drops `#section`).
587pub(crate) fn strip_wiki_link_decorations(link: &str) -> String {
588    let cleaned = link.trim_start_matches("[[").trim_end_matches("]]").trim();
589    let target = match cleaned.find('|') {
590        Some(i) => &cleaned[..i],
591        None => cleaned,
592    };
593    let target_no_anchor = match target.find('#') {
594        Some(i) => &target[..i],
595        None => target,
596    };
597    let target_no_dotdot = target_no_anchor.trim_start_matches("../");
598    target_no_dotdot
599        .strip_suffix(".md")
600        .unwrap_or(target_no_dotdot)
601        .to_string()
602}
603
604/// Compute the file path for an entity given its ID and base directory.
605/// The path is relative to the mem directory.
606///
607/// `specs--architecture/result-entity` → `architecture/result-entity.md`
608pub fn id_to_file_path(id: &EntityId) -> String {
609    format!("{}.md", id.path())
610}
611
612/// Validate that an `EntityId`'s path matches the wiki-link grammar
613/// (`^[\p{Ll}\p{Lo}\p{Lm}\p{N}-]+(/[\p{Ll}\p{Lo}\p{Lm}\p{N}-]+)*$`).
614/// Same regex the strict ingress validator applies to inline
615/// `[[...]]` targets — keeping the two gates aligned ensures the
616/// relate-target path doesn't admit ids that would fail an in-body
617/// wiki-link parse.
618///
619/// Accepted character classes match what [`title_to_slug`] produces:
620/// Unicode lowercase letters (`\p{Ll}`), case-less letters
621/// (`\p{Lo}` — CJK, Arabic, Hebrew, Devanagari, Thai, …), modifier
622/// letters (`\p{Lm}` — e.g. Japanese prolonged-sound mark `ー`),
623/// any Unicode numeric (`\p{N}`), and hyphen. Mem names stay
624/// ASCII — see [`validate_mem_name_grammar`]. F1 (option B+A).
625///
626/// Returns the original path on success, an error message on failure.
627/// Callers wrap the failure into a typed envelope (e.g.
628/// `INVALID_ENTITY_ID`).
629pub fn validate_id_path_grammar(path: &str) -> Result<&str, String> {
630    use std::sync::OnceLock;
631    static RE: OnceLock<regex::Regex> = OnceLock::new();
632    let re = RE.get_or_init(|| {
633        regex::Regex::new(
634            r"^[\p{Ll}\p{Lo}\p{Lm}\p{Mn}\p{Mc}\p{N}-]+(/[\p{Ll}\p{Lo}\p{Lm}\p{Mn}\p{Mc}\p{N}-]+)*$",
635        )
636        .unwrap()
637    });
638    if re.is_match(path) {
639        Ok(path)
640    } else {
641        Err(format!(
642            "id path '{path}' does not match the wiki-link grammar — \
643             entity slugs must be lowercase Unicode letters / digits / \
644             hyphens, with path segments separated by '/'"
645        ))
646    }
647}
648
649/// Validate a mem name (left side of `--`). Hierarchical paths are
650/// first-class: mem names accept `<segment>(/<segment>)*` where each
651/// segment matches the single-segment rule (`[a-z0-9-]+`). Leading slashes,
652/// trailing slashes, double slashes, and any character outside the
653/// allowed segment alphabet are explicit refusals.
654///
655/// Flat (single-segment) names work unchanged — the
656/// regex's `(/<segment>)*` tail matches zero or more times. The
657/// storage representation uses the full path for the
658/// `__MEMSTEAD` config blob (`__MEMSTEAD:mems/<path>/config.json`), the
659/// branch ref (`refs/heads/<path>`), and the in-memory router key.
660pub fn validate_mem_name_grammar(mem: &str) -> Result<&str, String> {
661    use std::sync::OnceLock;
662    static RE: OnceLock<regex::Regex> = OnceLock::new();
663    let re = RE.get_or_init(|| regex::Regex::new(r"^[a-z0-9-]+(/[a-z0-9-]+)*$").unwrap());
664    if re.is_match(mem) {
665        Ok(mem)
666    } else {
667        Err(format!(
668            "mem name '{mem}' must match ^[a-z0-9-]+(/[a-z0-9-]+)*$ \
669             (lowercase ASCII / digits / hyphens, optionally segmented \
670             by '/' for hierarchical layouts; no leading, trailing, or \
671             double slashes)"
672        ))
673    }
674}
675
676/// Validate relationship type. Input is case-insensitive and canonicalised
677/// to uppercase; only ASCII letters and underscores are permitted.
678pub fn validate_rel_type(rel_type: &str) -> Result<String, String> {
679    let cleaned = rel_type.to_uppercase();
680    if cleaned.chars().all(|c| c.is_ascii_uppercase() || c == '_') && !cleaned.is_empty() {
681        Ok(cleaned)
682    } else {
683        Err(format!(
684            "Invalid relationship type: \"{rel_type}\". Only ASCII letters and underscores allowed (input is canonicalised to uppercase)."
685        ))
686    }
687}
688
689#[cfg(test)]
690mod tests {
691    use super::*;
692
693    /// Mem-name grammar accepts hierarchical paths and refuses
694    /// malformations. Flat (single-segment) names continue to work —
695    /// the regex's `(/<segment>)*` tail matches zero or more times.
696    #[test]
697    fn validate_mem_name_grammar_accepts_hierarchical_paths() {
698        // Flat layouts (regression).
699        assert!(validate_mem_name_grammar("specs").is_ok());
700        assert!(validate_mem_name_grammar("my-mem").is_ok());
701        assert!(validate_mem_name_grammar("v1").is_ok());
702        // Hierarchical layouts.
703        assert!(validate_mem_name_grammar("team/sub-mem").is_ok());
704        assert!(validate_mem_name_grammar("a/b/c/d").is_ok());
705        assert!(validate_mem_name_grammar("planning/2026-q1").is_ok());
706    }
707
708    /// Grammar refusals are explicit. Each malformation
709    /// case (`/team`, `team/`, `team//sub`,
710    /// uppercase / underscore / dot) returns an `Err`.
711    #[test]
712    fn validate_mem_name_grammar_refuses_malformations() {
713        // Leading slash.
714        assert!(validate_mem_name_grammar("/team/sub").is_err());
715        // Trailing slash.
716        assert!(validate_mem_name_grammar("team/sub/").is_err());
717        // Double slash.
718        assert!(validate_mem_name_grammar("team//sub").is_err());
719        // Empty.
720        assert!(validate_mem_name_grammar("").is_err());
721        // Uppercase.
722        assert!(validate_mem_name_grammar("Team/Sub").is_err());
723        // Underscore (not in allowed alphabet).
724        assert!(validate_mem_name_grammar("team_sub").is_err());
725        assert!(validate_mem_name_grammar("team/sub_mem").is_err());
726        // Dot.
727        assert!(validate_mem_name_grammar("team.sub").is_err());
728        // Space.
729        assert!(validate_mem_name_grammar("team sub").is_err());
730    }
731
732    #[test]
733    fn title_to_slug_basic() {
734        assert_eq!(title_to_slug("My Entity").unwrap(), "my-entity");
735        assert_eq!(title_to_slug("My  Entity  Name").unwrap(), "my-entity-name");
736    }
737
738    /// F1 (B+A) behaviour change: precomposed Latin diacritics are
739    /// preserved in the slug rather than transliterated to ASCII.
740    /// `Große Änderung` was `grosse-aenderung` pre-F1; it is now
741    /// `große-änderung`. Same applies to `naïve`, `Café résumé`,
742    /// `Łódź`, etc. — slug matches title in every script the
743    /// Unicode `is_alphanumeric` predicate accepts.
744    #[test]
745    fn title_to_slug_german() {
746        assert_eq!(title_to_slug("Große Änderung").unwrap(), "große-änderung");
747        assert_eq!(title_to_slug("Björn").unwrap(), "björn");
748    }
749
750    #[test]
751    fn title_to_slug_diacritics() {
752        assert_eq!(title_to_slug("Café résumé").unwrap(), "café-résumé");
753        assert_eq!(title_to_slug("naïve").unwrap(), "naïve");
754    }
755
756    #[test]
757    fn title_to_slug_special_chars() {
758        assert_eq!(title_to_slug("Hello, World!").unwrap(), "hello-world");
759        assert_eq!(
760            title_to_slug("--leading--trailing--").unwrap(),
761            "leading-trailing"
762        );
763    }
764
765    #[test]
766    fn title_to_slug_polish() {
767        assert_eq!(title_to_slug("Łódź").unwrap(), "łódź");
768    }
769
770    /// F1 (B+A): CJK titles round-trip cleanly. No transliteration,
771    /// no hash — the slug equals the title.
772    #[test]
773    fn title_to_slug_cjk() {
774        assert_eq!(
775            title_to_slug("日本語のタイトル").unwrap(),
776            "日本語のタイトル"
777        );
778        // Spaces still collapse to hyphens.
779        assert_eq!(title_to_slug("中文 標題").unwrap(), "中文-標題");
780        // Mixed CJK + Latin + digits.
781        assert_eq!(title_to_slug("Project 日本 v2").unwrap(), "project-日本-v2");
782    }
783
784    /// F1 (B+A): cased non-Latin scripts (Cyrillic, Greek, Armenian)
785    /// case-fold to lowercase the same way Latin does.
786    #[test]
787    fn title_to_slug_cyrillic() {
788        assert_eq!(title_to_slug("Москва").unwrap(), "москва");
789        assert_eq!(title_to_slug("Москва-проект").unwrap(), "москва-проект");
790        assert_eq!(title_to_slug("ПРОЕКТ ПЛАН").unwrap(), "проект-план");
791    }
792
793    /// F1 (B+A): Right-to-left scripts. Hebrew and Arabic letters
794    /// are `\p{Lo}` (case-less); they pass through unchanged.
795    /// Hebrew niqqud and Arabic harakat are `\p{Mn}` (nonspacing
796    /// marks) carrying the Unicode `Other_Alphabetic` property, so
797    /// Rust's `is_alphanumeric` treats them as alphabetic and the
798    /// slug filter keeps them — wiki-link round-trip is exact for
799    /// titles that include vowelization. (The wiki-link regex
800    /// accepts the wider `\p{Mn}`/`\p{Mc}` class for the same
801    /// reason; see `slug_path_regex` in `validator/strict.rs`.)
802    #[test]
803    fn title_to_slug_rtl() {
804        // Hebrew with niqqud — niqqud is preserved; spaces become hyphens.
805        assert_eq!(title_to_slug("תַּפְקִיד עברי").unwrap(), "תַּפְקִיד-עברי");
806        // Arabic with harakat — harakat preserved (same Other_Alphabetic property).
807        assert_eq!(title_to_slug("مَرْحَبًا").unwrap(), "مَرْحَبًا");
808        // Plain Hebrew without vowelization (the more common case)
809        // round-trips letter-for-letter.
810        assert_eq!(title_to_slug("שלום עולם").unwrap(), "שלום-עולם");
811    }
812
813    /// F1 (option A backstop): titles whose pipeline yields an
814    /// empty slug fall through to a deterministic short-hash id
815    /// rather than failing. Covers all-emoji, all-symbol,
816    /// all-punctuation, and empty/whitespace inputs.
817    #[test]
818    fn title_to_slug_residual_falls_back_to_hash() {
819        // All emoji.
820        let emoji = title_to_slug("🚀✨").unwrap();
821        assert!(emoji.starts_with("entity-"), "got {emoji}");
822        assert_eq!(emoji.len(), "entity-".len() + 8);
823        // Same input always produces same hash (deterministic).
824        assert_eq!(emoji, title_to_slug("🚀✨").unwrap());
825        // Different inputs produce different hashes.
826        assert_ne!(emoji, title_to_slug("🌟").unwrap());
827
828        // Empty / whitespace / punctuation-only all hit the same path.
829        assert!(title_to_slug("").unwrap().starts_with("entity-"));
830        assert!(title_to_slug("   ").unwrap().starts_with("entity-"));
831        assert!(title_to_slug("\t\n").unwrap().starts_with("entity-"));
832        assert!(title_to_slug("---").unwrap().starts_with("entity-"));
833        assert!(title_to_slug("!!!").unwrap().starts_with("entity-"));
834        assert!(title_to_slug("!?.,;").unwrap().starts_with("entity-"));
835    }
836
837    /// NFC normalization is load-bearing for cross-platform safety:
838    /// a `Café` written NFD (`Cafe` + combining-acute U+0301) and
839    /// one written NFC (single codepoint U+00E9) must produce the
840    /// same slug. Pre-F1 the pipeline NFD-decomposed and stripped
841    /// combining marks, yielding `cafe` for both — that path is
842    /// gone, so the NFC normalization step is what holds the
843    /// invariant now.
844    #[test]
845    fn title_to_slug_nfc_normalization() {
846        let nfc = "Café"; // single-codepoint é
847        let nfd = "Cafe\u{0301}"; // e + combining acute
848        assert_ne!(nfc, nfd, "NFC and NFD forms must differ at the byte level");
849        assert_eq!(
850            title_to_slug(nfc).unwrap(),
851            title_to_slug(nfd).unwrap(),
852            "NFC and NFD inputs must produce the same slug",
853        );
854    }
855
856    /// F4: the strict mutation-entry gate rejects empty titles with
857    /// `TitleEmpty` so the wire envelope can carry `reason: "empty"`
858    /// rather than silently producing a hash-fallback slug.
859    #[test]
860    fn validate_and_derive_slug_rejects_empty() {
861        // `"\t\n"` is no longer here: it contains control characters, so
862        // the more specific control-char guard fires first (see
863        // `validate_and_derive_slug_rejects_control_chars`). These cases
864        // hold no control chars and collapse to an empty slug.
865        for empty in ["", "   ", "---", " - - - ", "-"] {
866            let err = validate_and_derive_slug(empty).unwrap_err();
867            let SlugError::TitleEmpty { input } = err else {
868                panic!("expected TitleEmpty for {empty:?}, got {err:?}");
869            };
870            assert_eq!(input, empty);
871        }
872    }
873
874    /// F10 + F19: any character the permissive pipeline would drop
875    /// (emoji, punctuation, math/currency symbols, path separators)
876    /// is admitted — the title is display text — with the dropped
877    /// characters reported and the slug derived exactly as the
878    /// permissive pipeline would (the old refusal's `proposed_slug`
879    /// is now simply the slug).
880    #[test]
881    fn validate_and_derive_slug_admits_and_reports_dropped_chars() {
882        let cases: &[(&str, &[char], &str)] = &[
883            ("Hello, World!", &[',', '!'], "hello-world"),
884            ("Café — résumé", &['—'], "café-résumé"),
885            ("🚀 launch", &['🚀'], "launch"),
886            ("price € 100", &['€'], "price-100"),
887            ("../escape", &['.', '/'], "escape"),
888            ("path/to/entity", &['/'], "pathtoentity"),
889            ("a\\b", &['\\'], "ab"),
890            ("Wohnung 2.OG rechts", &['.'], "wohnung-2og-rechts"),
891            (
892                "Anlage 4a – Leistungsbeschreibung",
893                &['–'],
894                "anlage-4a-leistungsbeschreibung",
895            ),
896            (
897                "Bösenberg Grundstücks GmbH & Co. KG",
898                &['&', '.'],
899                "bösenberg-grundstücks-gmbh-co-kg",
900            ),
901        ];
902        for (title, expected_dropped, expected_slug) in cases {
903            let got = validate_and_derive_slug(title)
904                .unwrap_or_else(|e| panic!("expected ok for {title:?}, got {e:?}"));
905            assert_eq!(got.slug, *expected_slug, "title={title:?}");
906            assert_eq!(got.dropped_chars, *expected_dropped, "title={title:?}");
907            // Byte-identical to the permissive pipeline, always.
908            assert_eq!(got.slug, title_to_slug(title).unwrap(), "title={title:?}");
909        }
910    }
911
912    /// F8: control characters (newline, tab,
913    /// carriage return, other C0 controls) are refused with
914    /// `TitleHasControlChars` rather than silently folded to hyphens —
915    /// they would otherwise split the stored `# H1` and truncate every
916    /// read of the title. The proposed slug is the single-line form.
917    #[test]
918    fn validate_and_derive_slug_rejects_control_chars() {
919        let cases: &[(&str, &[char], &str)] = &[
920            (
921                "Tab\tand\nnewline title",
922                &['\t', '\n'],
923                "tab-and-newline-title",
924            ),
925            ("line\rreturn", &['\r'], "line-return"),
926            ("null\u{0}byte", &['\u{0}'], "nullbyte"),
927        ];
928        for (title, expected_control, expected_proposed) in cases {
929            let err = validate_and_derive_slug(title).unwrap_err();
930            let SlugError::TitleHasControlChars {
931                input,
932                control_chars,
933                proposed_slug,
934            } = err
935            else {
936                panic!("expected TitleHasControlChars for {title:?}, got {err:?}");
937            };
938            assert_eq!(input, *title);
939            assert_eq!(control_chars, *expected_control, "title={title:?}");
940            assert_eq!(proposed_slug, *expected_proposed, "title={title:?}");
941        }
942    }
943
944    /// A plain space is whitespace but NOT a control character, so it
945    /// must keep folding to a hyphen (the control-char guard does not
946    /// narrow ordinary whitespace handling).
947    #[test]
948    fn validate_and_derive_slug_space_is_not_control() {
949        assert_eq!(validate_and_derive_slug("a b c").unwrap().slug, "a-b-c");
950    }
951
952    /// Success path — titles whose every character survives the
953    /// pipeline round-trip cleanly produce the same slug as
954    /// `title_to_slug` would.
955    #[test]
956    fn validate_and_derive_slug_success() {
957        let cases: &[(&str, &str)] = &[
958            ("My Entity", "my-entity"),
959            ("Große Änderung", "große-änderung"),
960            ("日本語のタイトル", "日本語のタイトル"),
961            ("--leading--trailing--", "leading-trailing"),
962            ("Project 日本 v2", "project-日本-v2"),
963        ];
964        for (title, expected) in cases {
965            let got = validate_and_derive_slug(title)
966                .unwrap_or_else(|e| panic!("expected ok for {title:?}, got {e:?}"));
967            assert_eq!(&got.slug, expected, "title={title:?}");
968            // A title the old grammar admitted drops nothing.
969            assert!(got.dropped_chars.is_empty(), "title={title:?}");
970            // Must agree with the permissive pipeline for accepted titles.
971            assert_eq!(got.slug, title_to_slug(title).unwrap(), "title={title:?}");
972        }
973    }
974
975    /// The strict gate runs the same NFC normalization as the
976    /// permissive pipeline, so NFC and NFD spellings of the same
977    /// title produce the same slug (or both reject).
978    #[test]
979    fn validate_and_derive_slug_nfc_normalization() {
980        let nfc = "Café";
981        let nfd = "Cafe\u{0301}";
982        assert_eq!(
983            validate_and_derive_slug(nfc).unwrap().slug,
984            validate_and_derive_slug(nfd).unwrap().slug,
985        );
986    }
987
988    /// SlugError::reason() returns the stable discriminator each
989    /// surface uses on the `details.reason` field.
990    #[test]
991    fn slug_error_reason_discriminator() {
992        let e = SlugError::TitleEmpty {
993            input: "".to_string(),
994        };
995        assert_eq!(e.reason(), "empty");
996        let e = SlugError::IdTooLong {
997            input: "specs--x".to_string(),
998            length: 201,
999            max: 200,
1000        };
1001        assert_eq!(e.reason(), "id_too_long");
1002        let e = SlugError::TitleHasControlChars {
1003            input: "a\nb".to_string(),
1004            control_chars: vec!['\n'],
1005            proposed_slug: "a-b".to_string(),
1006        };
1007        assert_eq!(e.reason(), "control_chars");
1008    }
1009
1010    /// F2 + F4: a title that derives a slug whose full
1011    /// `mem--slug` id sits at the 200-char ceiling is accepted;
1012    /// one byte over is rejected with a recovery-friendly error.
1013    /// `build_id` is the canonical write-side entry, so both
1014    /// behaviours land here.
1015    #[test]
1016    fn build_id_enforces_length_cap() {
1017        let mem = "specs";
1018        // mem.len()=5, "--"=2 → 7-char prefix. Slug of 193 chars
1019        // produces a 200-char id; 194 chars trips the cap.
1020        let just_fits = "a".repeat(ENTITY_ID_MAX_LEN - mem.len() - 2);
1021        let ok = build_id(mem, &just_fits).expect("at-cap id must pass");
1022        assert_eq!(ok.as_ref().chars().count(), ENTITY_ID_MAX_LEN);
1023
1024        let one_over = "a".repeat(ENTITY_ID_MAX_LEN - mem.len() - 2 + 1);
1025        let err = build_id(mem, &one_over).unwrap_err();
1026        let SlugError::IdTooLong { input, length, max } = err else {
1027            panic!("expected IdTooLong, got {err:?}");
1028        };
1029        // `input` echoes the composed id, not the title, so it agrees
1030        // with `length`.
1031        assert_eq!(input, format!("{mem}--{one_over}"));
1032        assert_eq!(input.chars().count(), length);
1033        assert_eq!(length, ENTITY_ID_MAX_LEN + 1);
1034        assert_eq!(max, ENTITY_ID_MAX_LEN);
1035    }
1036
1037    #[test]
1038    fn build_id_basic() {
1039        assert_eq!(
1040            build_id("specs", "My Entity").unwrap().0,
1041            "specs--my-entity"
1042        );
1043    }
1044
1045    /// F1 (B+A): non-Latin titles round-trip through `build_id`.
1046    #[test]
1047    fn build_id_non_latin() {
1048        assert_eq!(
1049            build_id("specs", "日本語のタイトル").unwrap().0,
1050            "specs--日本語のタイトル",
1051        );
1052        assert_eq!(
1053            build_id("specs", "Москва-проект").unwrap().0,
1054            "specs--москва-проект",
1055        );
1056    }
1057
1058    #[test]
1059    fn file_path_to_id_basic() {
1060        assert_eq!(
1061            file_path_to_id("architecture/result-entity.md", "specs").0,
1062            "specs--architecture/result-entity"
1063        );
1064        assert_eq!(
1065            file_path_to_id("result-entity.md", "specs").0,
1066            "specs--result-entity"
1067        );
1068    }
1069
1070    #[test]
1071    fn wiki_link_to_id_basic() {
1072        assert_eq!(
1073            wiki_link_to_id("result-entity", "specs").unwrap().0,
1074            "specs--result-entity"
1075        );
1076        assert_eq!(
1077            wiki_link_to_id("parent/child/entity", "specs").unwrap().0,
1078            "specs--parent/child/entity"
1079        );
1080    }
1081
1082    #[test]
1083    fn wiki_link_to_id_strips_alias() {
1084        assert_eq!(
1085            wiki_link_to_id("target|Display Name", "specs").unwrap().0,
1086            "specs--target"
1087        );
1088    }
1089
1090    #[test]
1091    fn wiki_link_to_id_strips_prefix_and_suffix() {
1092        assert_eq!(
1093            wiki_link_to_id("../parent/entity.md", "specs").unwrap().0,
1094            "specs--parent/entity"
1095        );
1096    }
1097
1098    /// Agents writing the canonical fully-qualified id `[[mem--slug]]`
1099    /// must not be doubly-prefixed into `mem--mem--slug`.
1100    #[test]
1101    fn wiki_link_to_id_strips_redundant_self_prefix() {
1102        assert_eq!(
1103            wiki_link_to_id("specs--result-entity", "specs").unwrap().0,
1104            "specs--result-entity"
1105        );
1106        assert_eq!(
1107            wiki_link_to_id("test-mem-mini--engine", "test-mem-mini")
1108                .unwrap()
1109                .0,
1110            "test-mem-mini--engine"
1111        );
1112        assert_eq!(
1113            wiki_link_to_id("specs--target.md|Display", "specs")
1114                .unwrap()
1115                .0,
1116            "specs--target"
1117        );
1118        assert_eq!(
1119            wiki_link_to_id("specs--parent/child", "specs").unwrap().0,
1120            "specs--parent/child"
1121        );
1122        // Self-prefix stripping is one-shot, not iterative — a second
1123        // embedded `<current_mem>--` is preserved so cross-mem-style
1124        // drift stays visible.
1125        assert_eq!(
1126            wiki_link_to_id("specs--specs--slug", "specs").unwrap().0,
1127            "specs--specs--slug"
1128        );
1129    }
1130
1131    /// Cross-mem dash form `[[<mem>--<slug>]]` routes to the named
1132    /// mem rather than silently re-prepending the source mem into a
1133    /// phantom `specs--other--entity` stub.
1134    /// The cross-mem policy gate (alias-synthesis pass) refuses the
1135    /// auto-stub when the workspace policy denies the direction —
1136    /// that gate is exercised in engine-layer tests.
1137    #[test]
1138    fn wiki_link_to_id_tier_zero_cross_mem_dash_form() {
1139        assert_eq!(
1140            wiki_link_to_id("other--entity", "specs").unwrap().0,
1141            "other--entity"
1142        );
1143        assert_eq!(
1144            wiki_link_to_id("nonexistent-mem--target", "specs")
1145                .unwrap()
1146                .0,
1147            "nonexistent-mem--target"
1148        );
1149    }
1150
1151    /// Tier-0 dash form collapses cleanly when the named mem is the
1152    /// source mem — equivalent to the self-prefix-strip fast path
1153    /// for bare-slug authoring.
1154    #[test]
1155    fn wiki_link_to_id_tier_zero_self_mem_dash_form() {
1156        assert_eq!(
1157            wiki_link_to_id("specs--target", "specs").unwrap().0,
1158            "specs--target"
1159        );
1160    }
1161
1162    /// Tier-0 only admits single-segment mem names — the
1163    /// hierarchical dash form stays on the colon Tier-2 recovery
1164    /// path. The pre-existing slash-dash ambiguity refusal is what
1165    /// fires here (cross-mem into a hierarchical mem is
1166    /// grammatically ambiguous with a same-mem hierarchical slug).
1167    #[test]
1168    fn wiki_link_to_id_tier_zero_refuses_hierarchical_prefix() {
1169        let err = wiki_link_to_id("team/sub-mem--target", "specs").unwrap_err();
1170        match err {
1171            WikiLinkError::InvalidTarget { suggested, .. } => {
1172                assert_eq!(suggested.as_deref(), Some("team/sub-mem:target"));
1173            }
1174            other => panic!("expected InvalidTarget, got {other:?}"),
1175        }
1176    }
1177
1178    /// Section anchors strip as a display decoration alongside `|alias`,
1179    /// `../`, and `.md`. Single anchor, multi-anchor, and the
1180    /// combined anchor+alias form all collapse to the underlying
1181    /// slug-form id.
1182    #[test]
1183    fn wiki_link_to_id_strips_section_anchor() {
1184        assert_eq!(
1185            wiki_link_to_id("login-service#identity", "specs")
1186                .unwrap()
1187                .0,
1188            "specs--login-service"
1189        );
1190        assert_eq!(
1191            wiki_link_to_id("specs--login-service#identity", "specs")
1192                .unwrap()
1193                .0,
1194            "specs--login-service"
1195        );
1196        // Multi-anchor — strip from first `#`.
1197        assert_eq!(
1198            wiki_link_to_id("specs--target#a#b", "specs").unwrap().0,
1199            "specs--target"
1200        );
1201        // Combined anchor + alias.
1202        assert_eq!(
1203            wiki_link_to_id("specs--target#section|Display", "specs")
1204                .unwrap()
1205                .0,
1206            "specs--target"
1207        );
1208    }
1209
1210    /// Cross-mem routing and anchor stripping compose: a cross-mem
1211    /// anchored form resolves under tier-0 and strips the anchor.
1212    #[test]
1213    fn wiki_link_to_id_cross_mem_anchored_composes() {
1214        assert_eq!(
1215            wiki_link_to_id("other--target#section", "specs").unwrap().0,
1216            "other--target"
1217        );
1218    }
1219
1220    /// Empty `current_mem` opts out of self-prefix stripping so a
1221    /// literal leading `--` (which would never legitimately occur, but
1222    /// could collide with `format!("{mem}--", mem="")`) stays intact.
1223    #[test]
1224    fn wiki_link_to_id_empty_mem_does_not_strip() {
1225        assert_eq!(wiki_link_to_id("--weird", "").unwrap().0, "----weird");
1226    }
1227
1228    #[test]
1229    fn wiki_link_to_id_tier_two_cross_mem() {
1230        assert_eq!(
1231            wiki_link_to_id("engine:health", "plugin").unwrap().0,
1232            "engine--health"
1233        );
1234        assert_eq!(
1235            wiki_link_to_id("engine:architecture/result", "plugin")
1236                .unwrap()
1237                .0,
1238            "engine--architecture/result"
1239        );
1240    }
1241
1242    #[test]
1243    fn wiki_link_to_id_tier_two_self_prefix_collapses() {
1244        assert_eq!(
1245            wiki_link_to_id("specs:foo", "specs").unwrap().0,
1246            "specs--foo"
1247        );
1248        assert_eq!(
1249            wiki_link_to_id("specs:foo", "specs").unwrap(),
1250            wiki_link_to_id("foo", "specs").unwrap()
1251        );
1252    }
1253
1254    #[test]
1255    fn wiki_link_to_id_tier_two_combines_with_alias_and_md() {
1256        assert_eq!(
1257            wiki_link_to_id("engine:health.md|See health", "plugin")
1258                .unwrap()
1259                .0,
1260            "engine--health"
1261        );
1262    }
1263
1264    #[test]
1265    fn wiki_link_to_id_tier_two_accepts_hierarchical_prefix() {
1266        assert_eq!(
1267            wiki_link_to_id("external/engine:health", "plugin")
1268                .unwrap()
1269                .0,
1270            "external/engine--health"
1271        );
1272    }
1273
1274    #[test]
1275    fn wiki_link_to_id_tier_one_strips_hierarchical_self_prefix() {
1276        assert_eq!(
1277            wiki_link_to_id("team/sub-mem--auth-service", "team/sub-mem")
1278                .unwrap()
1279                .0,
1280            "team/sub-mem--auth-service"
1281        );
1282    }
1283
1284    #[test]
1285    fn wiki_link_to_id_tier_one_bare_slug_from_hierarchical_mem() {
1286        assert_eq!(
1287            wiki_link_to_id("auth-service", "team/sub-mem").unwrap().0,
1288            "team/sub-mem--auth-service"
1289        );
1290    }
1291
1292    /// `::` is reserved syntax — strict refusal. The slug-grammar gate
1293    /// refuses the `:` character outright.
1294    #[test]
1295    fn wiki_link_to_id_double_colon_refuses() {
1296        let err = wiki_link_to_id("engine::health", "plugin").unwrap_err();
1297        assert!(
1298            matches!(err, WikiLinkError::InvalidTarget { .. }),
1299            "got {err:?}"
1300        );
1301    }
1302
1303    /// Empty halves around the colon refuse under strict mode — the
1304    /// `:` character isn't in the slug-grammar character class, so
1305    /// the Tier-1 fallback fails.
1306    #[test]
1307    fn wiki_link_to_id_empty_tier_two_halves_refuse() {
1308        assert!(matches!(
1309            wiki_link_to_id(":foo", "specs").unwrap_err(),
1310            WikiLinkError::InvalidTarget { .. }
1311        ));
1312        assert!(matches!(
1313            wiki_link_to_id("engine:", "specs").unwrap_err(),
1314            WikiLinkError::InvalidTarget { .. }
1315        ));
1316    }
1317
1318    /// Natural-form (uppercase + whitespace) refuses with
1319    /// `InvalidTarget` and a `title_to_slug`-derived suggestion the
1320    /// agent lifts directly into a retry.
1321    #[test]
1322    fn wiki_link_to_id_natural_form_refuses_with_suggestion() {
1323        let err = wiki_link_to_id("Knowledge Graph", "specs").unwrap_err();
1324        let WikiLinkError::InvalidTarget { raw, suggested, .. } = err else {
1325            panic!("expected InvalidTarget, got {err:?}");
1326        };
1327        assert_eq!(raw, "Knowledge Graph");
1328        assert_eq!(suggested.as_deref(), Some("knowledge-graph"));
1329    }
1330
1331    /// Tier-2 with natural-form slug suggests `mem:slug`
1332    /// preserving the prefix. The agent rewrites only the slug part.
1333    #[test]
1334    fn wiki_link_to_id_tier_two_natural_slug_refuses_with_prefixed_suggestion() {
1335        let err = wiki_link_to_id("engine:Health Check", "plugin").unwrap_err();
1336        let WikiLinkError::InvalidTarget { raw, suggested, .. } = err else {
1337            panic!("expected InvalidTarget, got {err:?}");
1338        };
1339        assert_eq!(raw, "engine:Health Check");
1340        assert_eq!(suggested.as_deref(), Some("engine:health-check"));
1341    }
1342
1343    /// Tier-1 dash form
1344    /// with `/` in the would-be mem prefix is grammatically
1345    /// ambiguous (cross-mem into a hierarchical mem vs same-mem
1346    /// hierarchical slug). Refusal carries the colon-form as
1347    /// `suggested` so the agent's recovery is a one-character edit.
1348    #[test]
1349    fn wiki_link_to_id_hierarchical_dash_form_refuses_with_colon_suggestion() {
1350        let err = wiki_link_to_id("team/sub-mem--auth-service", "test").unwrap_err();
1351        let WikiLinkError::InvalidTarget {
1352            raw,
1353            suggested,
1354            reason,
1355        } = err
1356        else {
1357            panic!("expected InvalidTarget, got {err:?}");
1358        };
1359        assert_eq!(raw, "team/sub-mem--auth-service");
1360        assert_eq!(suggested.as_deref(), Some("team/sub-mem:auth-service"));
1361        // Reason names both disambiguations.
1362        assert!(
1363            reason.contains("team/sub-mem:auth-service"),
1364            "reason must surface the cross-mem colon form: {reason}"
1365        );
1366        assert!(
1367            reason.contains("test:team/sub-mem--auth-service"),
1368            "reason must surface the same-mem hierarchical form: {reason}"
1369        );
1370    }
1371
1372    /// For self-prefixed dash form, tier-0 splits on the FIRST `--`, so
1373    /// `[[test--team/sub--target]]` resolves as mem `test`, slug
1374    /// `team/sub--target` — a same-mem entity with a hierarchical
1375    /// slug containing `--`. The ambiguity gate in the slug position
1376    /// does not apply because the mem/slug boundary is
1377    /// pinned by tier-0's grammar.
1378    #[test]
1379    fn wiki_link_to_id_self_prefixed_dash_form_resolves_via_tier_zero() {
1380        let id = wiki_link_to_id("test--team/sub--target", "test").unwrap();
1381        assert_eq!(id.mem(), "test");
1382        assert_eq!(id.path(), "team/sub--target");
1383    }
1384
1385    /// A bare hierarchical slug (no `--`) continues to
1386    /// resolve to a same-mem entity. The refusal is keyed on the
1387    /// simultaneous presence of `/` AND `--`, not on `/` alone.
1388    #[test]
1389    fn wiki_link_to_id_bare_hierarchical_slug_still_resolves() {
1390        let id = wiki_link_to_id("team/sub-mem", "test").unwrap();
1391        assert_eq!(id.mem(), "test");
1392        assert_eq!(id.path(), "team/sub-mem");
1393    }
1394
1395    /// Colon-form for cross-mem hierarchical reference
1396    /// continues to resolve correctly (the canonical disambiguation).
1397    #[test]
1398    fn wiki_link_to_id_hierarchical_colon_form_resolves_cross_mem() {
1399        let id = wiki_link_to_id("team/sub-mem:auth-service", "test").unwrap();
1400        assert_eq!(id.mem(), "team/sub-mem");
1401        assert_eq!(id.path(), "auth-service");
1402    }
1403
1404    /// Flat `[[<other-mem>--<slug>]]` routes to the named mem under
1405    /// tier-0 rather than silently re-prefixing with the source mem into
1406    /// a phantom `test--other--target` stub. The cross-mem policy
1407    /// gate enforces routing legality in the alias-synthesis pass —
1408    /// that gate is exercised in engine-layer tests.
1409    #[test]
1410    fn wiki_link_to_id_flat_foreign_dash_form_routes_via_tier_zero() {
1411        let id = wiki_link_to_id("other--target", "test").unwrap();
1412        assert_eq!(id.mem(), "other");
1413        assert_eq!(id.path(), "target");
1414    }
1415
1416    /// Tier-2 with non-ASCII mem prefix refuses with
1417    /// `InvalidMemName`. Mem names are ASCII-only operator
1418    /// identifiers; the agent cannot auto-slugify them.
1419    #[test]
1420    fn wiki_link_to_id_tier_two_bad_mem_refuses_with_distinct_error() {
1421        let err = wiki_link_to_id("Other Mem:foo", "plugin").unwrap_err();
1422        let WikiLinkError::InvalidMemName { raw, .. } = err else {
1423            panic!("expected InvalidMemName, got {err:?}");
1424        };
1425        assert_eq!(raw, "Other Mem");
1426    }
1427
1428    /// Pathological inputs (empty, all punctuation) refuse
1429    /// with `suggested: None`.
1430    #[test]
1431    fn wiki_link_to_id_pathological_input_no_suggestion() {
1432        let err = wiki_link_to_id("!!!", "specs").unwrap_err();
1433        let WikiLinkError::InvalidTarget { suggested, .. } = err else {
1434            panic!("expected InvalidTarget, got {err:?}");
1435        };
1436        assert!(suggested.is_none(), "got {suggested:?}");
1437    }
1438
1439    /// Slug-form across every script family the slug
1440    /// pipeline accepts round-trips through the strict gate.
1441    #[test]
1442    fn wiki_link_to_id_accepts_slug_form_across_scripts() {
1443        let cases: &[(&str, &str)] = &[
1444            ("knowledge-graph", "v--knowledge-graph"),
1445            ("الرسم-البياني-للمعرفة", "v--الرسم-البياني-للمعرفة"),
1446            ("ज्ञान-ग्राफ", "v--ज्ञान-ग्राफ"),
1447            ("知识图谱", "v--知识图谱"),
1448            ("知識グラフ", "v--知識グラフ"),
1449            ("กราฟความรู้", "v--กราฟความรู้"),
1450            ("ידע-גרף", "v--ידע-גרף"),
1451        ];
1452        for (input, expected) in cases {
1453            let id = wiki_link_to_id(input, "v")
1454                .unwrap_or_else(|e| panic!("expected ok for {input:?}, got {e:?}"));
1455            assert_eq!(&id.0, expected, "input={input:?}");
1456        }
1457    }
1458
1459    /// The lenient decoder preserves pre-strict behaviour
1460    /// for read-side scanners that must tolerate on-disk drift.
1461    /// Round-trip equivalence on the inputs the strict gate accepts.
1462    #[test]
1463    fn wiki_link_to_id_lenient_matches_strict_on_valid_input() {
1464        let inputs = &["knowledge-graph", "engine:health", "parent/child"];
1465        for input in inputs {
1466            let strict = wiki_link_to_id(input, "specs").unwrap();
1467            let lenient = wiki_link_to_id_lenient(input, "specs");
1468            assert_eq!(strict, lenient, "input={input:?}");
1469        }
1470    }
1471
1472    /// The lenient decoder accepts what the strict gate
1473    /// refuses, surfacing the literal drift for read-side reporting.
1474    #[test]
1475    fn wiki_link_to_id_lenient_admits_drift() {
1476        assert_eq!(
1477            wiki_link_to_id_lenient("Knowledge Graph", "specs").0,
1478            "specs--Knowledge Graph"
1479        );
1480        assert_eq!(
1481            wiki_link_to_id_lenient("engine::health", "plugin").0,
1482            "plugin--engine::health"
1483        );
1484    }
1485
1486    #[test]
1487    fn entity_id_parts() {
1488        let id = EntityId::new("specs", "parent/child");
1489        assert_eq!(id.mem(), "specs");
1490        assert_eq!(id.path(), "parent/child");
1491        assert_eq!(id.name(), "child");
1492    }
1493
1494    #[test]
1495    fn entity_id_no_mem() {
1496        let id = EntityId("result-entity".to_string());
1497        assert_eq!(id.mem(), "");
1498        assert_eq!(id.path(), "result-entity");
1499        assert_eq!(id.name(), "result-entity");
1500    }
1501
1502    #[test]
1503    fn id_to_file_path_basic() {
1504        let id = EntityId::new("specs", "architecture/result-entity");
1505        assert_eq!(id_to_file_path(&id), "architecture/result-entity.md");
1506    }
1507
1508    #[test]
1509    fn validate_rel_type_valid() {
1510        assert_eq!(validate_rel_type("PART_OF").unwrap(), "PART_OF");
1511        assert_eq!(validate_rel_type("uses").unwrap(), "USES");
1512    }
1513
1514    #[test]
1515    fn validate_rel_type_invalid() {
1516        assert!(validate_rel_type("has spaces").is_err());
1517        assert!(validate_rel_type("").is_err());
1518    }
1519
1520    /// TITLE_GRAMMAR_RULE conformance: the documented sentence and the
1521    /// validator agree — any single-line text is admitted, characters
1522    /// outside the slug alphabet are dropped from the slug and
1523    /// reported, and control characters are the rejection. If this
1524    /// test fails, either the validator's behaviour or the constant
1525    /// changed alone; change them together.
1526    #[test]
1527    fn title_grammar_rule_matches_validator_behaviour() {
1528        // Admitted with nothing dropped: Unicode alphanumerics,
1529        // whitespace, hyphen.
1530        for ok in [
1531            "Plain Title",
1532            "hyphen-ated",
1533            "Große Änderung", // non-ASCII alphanumerics
1534            "日本語 タイトル",
1535            "nbsp\u{a0}space", // non-control whitespace folds to hyphen
1536        ] {
1537            let got = validate_and_derive_slug(ok)
1538                .unwrap_or_else(|e| panic!("rule says {ok:?} is accepted, got {e:?}"));
1539            assert!(got.dropped_chars.is_empty(), "{ok:?} drops nothing");
1540        }
1541        // Admitted per the rule, with characters outside the slug
1542        // alphabet dropped from the slug and reported — the plenum
1543        // collision list plus representative symbol/punctuation cases.
1544        for (title, dropped) in [
1545            ("v1.0", '.'),
1546            ("a (draft)", '('),
1547            ("a (draft", '('),
1548            ("either/or", '/'),
1549            ("re: title", ':'),
1550            ("a \u{2014} b", '\u{2014}'), // em dash
1551            ("hello!", '!'),
1552        ] {
1553            let got = validate_and_derive_slug(title)
1554                .unwrap_or_else(|e| panic!("rule says {title:?} is admitted, got {e:?}"));
1555            assert!(
1556                got.dropped_chars.contains(&dropped),
1557                "{title:?}: the divergence report names {dropped:?}, got {:?}",
1558                got.dropped_chars
1559            );
1560            assert!(
1561                !got.slug.is_empty(),
1562                "{title:?}: a slug still derives from the surviving characters"
1563            );
1564        }
1565        // Control-class whitespace (tab, newline) is the rejection,
1566        // per the rule's parenthetical.
1567        for title in ["tabs\tinside", "line\nbreak"] {
1568            assert!(
1569                matches!(
1570                    validate_and_derive_slug(title),
1571                    Err(SlugError::TitleHasControlChars { .. })
1572                ),
1573                "rule says {title:?} is rejected as a control character"
1574            );
1575        }
1576    }
1577}