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 (`garden`) — 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 // Strip decorations and trim to a FIXPOINT: each pass can expose
531 // work for another — an alias/anchor cut exposes trailing
532 // whitespace (`foo |label` → `foo `), and trimming that whitespace
533 // can expose a `.md` suffix the pass could not see (`x.md\r` →
534 // `x.md` → `x`; fuzz finding, corpus member `crash-b256aad3…`).
535 // The tolerant path must land on ids the generator round-trips
536 // (parse→generate is a fixpoint after one round), so it normalises
537 // until nothing changes. The loop terminates because every pass
538 // only ever shortens the string. Deliberately NOT in the shared
539 // helper: the strict decoder runs one pass and its grammar gate
540 // still refuses the leftover shapes.
541 let mut stripped = strip_wiki_link_decorations(link);
542 loop {
543 let next = strip_wiki_link_decorations(stripped.trim_end());
544 if next == stripped {
545 break;
546 }
547 stripped = next;
548 }
549 let stripped = stripped.trim_end();
550
551 if !stripped.contains("::")
552 && let Some(colon_idx) = stripped.find(':')
553 {
554 let (prefix, rest) = stripped.split_at(colon_idx);
555 let slug_part = &rest[1..];
556 if !prefix.is_empty() && !slug_part.is_empty() {
557 return EntityId::new(prefix, slug_part);
558 }
559 }
560
561 // Tier 0 — cross-mem dash form. Read-side mirror of the strict
562 // decoder's recognition so dangling-link reports and graph
563 // inspectors interpret on-disk `[[other--target]]` the same way
564 // the mutation gate writes it. Pre-strict drift on older entities
565 // keeps the bare-slug fallback below for
566 // shapes the tier-0 doesn't admit (empty prefix, hierarchical
567 // prefix, malformed slug).
568 if let Some(dash_idx) = stripped.find("--") {
569 let prefix = &stripped[..dash_idx];
570 let suffix = &stripped[dash_idx + 2..];
571 if !prefix.is_empty()
572 && !suffix.is_empty()
573 && !prefix.contains('/')
574 && validate_mem_name_grammar(prefix).is_ok()
575 && validate_id_path_grammar(suffix).is_ok()
576 {
577 return EntityId::new(prefix, suffix);
578 }
579 }
580
581 let slug = if !current_mem.is_empty() {
582 let self_prefix = format!("{current_mem}--");
583 stripped
584 .strip_prefix(self_prefix.as_str())
585 .unwrap_or(stripped)
586 } else {
587 stripped
588 };
589 EntityId::new(current_mem, slug)
590}
591
592/// Strip `[[`/`]]`, the Obsidian alias suffix `|display`, the section
593/// anchor `#section` (plus any trailing `#sub` etc — stripped from the
594/// first `#` onward), leading `../` segments, and the trailing `.md`
595/// suffix from a raw wiki-link token. Shared by the strict and
596/// lenient decoders so the pre-grammar-gate textual normalisation is
597/// byte-equivalent on both paths.
598///
599/// `#anchor` strip: Obsidian-style section anchors are display-only at
600/// the graph layer; the engine has no semantic use for them. Strip
601/// from the first `#` onward so multi-anchor forms like
602/// `target#a#b` collapse to `target` in one pass. Ordered after the
603/// `|alias` strip so `target#section|display` correctly drops both
604/// (the alias strip drops `|display` first, leaving `target#section`;
605/// the anchor strip then drops `#section`).
606pub(crate) fn strip_wiki_link_decorations(link: &str) -> String {
607 let cleaned = link.trim_start_matches("[[").trim_end_matches("]]").trim();
608 let target = match cleaned.find('|') {
609 Some(i) => &cleaned[..i],
610 None => cleaned,
611 };
612 let target_no_anchor = match target.find('#') {
613 Some(i) => &target[..i],
614 None => target,
615 };
616 let target_no_dotdot = target_no_anchor.trim_start_matches("../");
617 target_no_dotdot
618 .strip_suffix(".md")
619 .unwrap_or(target_no_dotdot)
620 .to_string()
621}
622
623/// Compute the file path for an entity given its ID and base directory.
624/// The path is relative to the mem directory.
625///
626/// `specs--architecture/result-entity` → `architecture/result-entity.md`
627pub fn id_to_file_path(id: &EntityId) -> String {
628 format!("{}.md", id.path())
629}
630
631/// Validate that an `EntityId`'s path matches the wiki-link grammar
632/// (`^[\p{Ll}\p{Lo}\p{Lm}\p{N}-]+(/[\p{Ll}\p{Lo}\p{Lm}\p{N}-]+)*$`).
633/// Same regex the strict ingress validator applies to inline
634/// `[[...]]` targets — keeping the two gates aligned ensures the
635/// relate-target path doesn't admit ids that would fail an in-body
636/// wiki-link parse.
637///
638/// Accepted character classes match what [`title_to_slug`] produces:
639/// Unicode lowercase letters (`\p{Ll}`), case-less letters
640/// (`\p{Lo}` — CJK, Arabic, Hebrew, Devanagari, Thai, …), modifier
641/// letters (`\p{Lm}` — e.g. Japanese prolonged-sound mark `ー`),
642/// any Unicode numeric (`\p{N}`), and hyphen. Mem names stay
643/// ASCII — see [`validate_mem_name_grammar`]. F1 (option B+A).
644///
645/// Returns the original path on success, an error message on failure.
646/// Callers wrap the failure into a typed envelope (e.g.
647/// `INVALID_ENTITY_ID`).
648pub fn validate_id_path_grammar(path: &str) -> Result<&str, String> {
649 use std::sync::OnceLock;
650 static RE: OnceLock<regex::Regex> = OnceLock::new();
651 let re = RE.get_or_init(|| {
652 regex::Regex::new(
653 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}-]+)*$",
654 )
655 .unwrap()
656 });
657 if re.is_match(path) {
658 Ok(path)
659 } else {
660 Err(format!(
661 "id path '{path}' does not match the wiki-link grammar — \
662 entity slugs must be lowercase Unicode letters / digits / \
663 hyphens, with path segments separated by '/'"
664 ))
665 }
666}
667
668/// Validate a mem name (left side of `--`). Hierarchical paths are
669/// first-class: mem names accept `<segment>(/<segment>)*` where each
670/// segment matches the single-segment rule (`[a-z0-9-]+`). Leading slashes,
671/// trailing slashes, double slashes, and any character outside the
672/// allowed segment alphabet are explicit refusals.
673///
674/// Flat (single-segment) names work unchanged — the
675/// regex's `(/<segment>)*` tail matches zero or more times. The
676/// storage representation uses the full path for the
677/// `__MEMSTEAD` config blob (`__MEMSTEAD:mems/<path>/config.json`), the
678/// branch ref (`refs/heads/<path>`), and the in-memory router key.
679pub fn validate_mem_name_grammar(mem: &str) -> Result<&str, String> {
680 use std::sync::OnceLock;
681 static RE: OnceLock<regex::Regex> = OnceLock::new();
682 let re = RE.get_or_init(|| regex::Regex::new(r"^[a-z0-9-]+(/[a-z0-9-]+)*$").unwrap());
683 if re.is_match(mem) {
684 Ok(mem)
685 } else {
686 Err(format!(
687 "mem name '{mem}' must match ^[a-z0-9-]+(/[a-z0-9-]+)*$ \
688 (lowercase ASCII / digits / hyphens, optionally segmented \
689 by '/' for hierarchical layouts; no leading, trailing, or \
690 double slashes)"
691 ))
692 }
693}
694
695/// Validate relationship type. Input is case-insensitive and canonicalised
696/// to uppercase; only ASCII letters and underscores are permitted.
697pub fn validate_rel_type(rel_type: &str) -> Result<String, String> {
698 let cleaned = rel_type.to_uppercase();
699 if cleaned.chars().all(|c| c.is_ascii_uppercase() || c == '_') && !cleaned.is_empty() {
700 Ok(cleaned)
701 } else {
702 Err(format!(
703 "Invalid relationship type: \"{rel_type}\". Only ASCII letters and underscores allowed (input is canonicalised to uppercase)."
704 ))
705 }
706}
707
708#[cfg(test)]
709mod tests;