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.
12pub const ENTITY_ID_MAX_LEN: usize = 200;
13
14/// Error cases for title→slug derivation. `title_to_slug` itself is
15/// total — any title produces a slug (residual cases like
16/// all-emoji collapse to a deterministic short-hash id) — so it never
17/// returns these variants directly. The strict mutation-entry gate
18/// [`validate_and_derive_slug`] returns them for control characters
19/// and for input that would have fallen back to the hash slug;
20/// [`enforce_id_length`] returns [`Self::IdTooLong`] when the
21/// derived `mem--slug` exceeds the read-path length cap.
22///
23/// Loader and parse paths continue to call [`title_to_slug`] so
24/// pre-gate entities created with the old permissive pipeline remain
25/// readable.
26#[derive(Debug, thiserror::Error)]
27pub enum SlugError {
28 /// The derived `mem--slug` id exceeds [`ENTITY_ID_MAX_LEN`]. The
29 /// read-path validator rejects ids past this length, so without
30 /// this guard a title that the write path accepts produces an
31 /// entity that is silently unreachable on read.
32 ///
33 /// The bound is on the **composed id** (`<mem>--<slug>`), which is
34 /// also the on-disk filename — so the budget is mem-name-dependent
35 /// and the same title can be valid in a short-named mem and rejected
36 /// in a longer-named one. `input` echoes that composed id (not the
37 /// title) so it agrees with `length`: the payload measures one
38 /// quantity, the id, end to end. `max` is [`ENTITY_ID_MAX_LEN`] so the
39 /// agent can shorten by the exact delta.
40 #[error(
41 "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"
42 )]
43 IdTooLong {
44 /// The composed `<mem>--<slug>` id whose length exceeded the
45 /// cap. Echoed as the `input` wire field so `input` and `length`
46 /// describe the same measured quantity.
47 input: String,
48 length: usize,
49 max: usize,
50 },
51 /// Strict mutation-entry rejection: the title is empty,
52 /// whitespace-only, or composed exclusively of pipeline-separator
53 /// characters (hyphens) so the slug pipeline would have collapsed
54 /// it to a hash-fallback id. Recovery: supply a non-empty title
55 /// with at least one alphanumeric character.
56 #[error("title is empty or contains no slug-meaningful characters")]
57 TitleEmpty { input: String },
58 /// Strict mutation-entry rejection: the title contains control
59 /// characters (newline, tab, other C0/C1 controls). These are
60 /// Unicode whitespace, so the slug pipeline silently folds them to
61 /// hyphens and accepts the title — but they survive verbatim into the
62 /// stored `# H1` heading, which then splits across lines so every
63 /// read truncates the title at the first control char (search and
64 /// `memstead_entity` see only the prefix). Refused up front with the same
65 /// named-offenders + `proposed_slug` recovery shape the invalid-char
66 /// guard uses. `control_chars` lists each distinct offender in source
67 /// order; `proposed_slug` is the slug the pipeline would produce, for
68 /// a mechanical retry with a single-line title.
69 #[error(
70 "title {input:?} contains control character(s) {control_chars:?} that would split the stored heading — \
71 retry with a single-line title (proposed slug: \"{proposed_slug}\")"
72 )]
73 TitleHasControlChars {
74 input: String,
75 control_chars: Vec<char>,
76 proposed_slug: String,
77 },
78}
79
80impl SlugError {
81 /// Stable discriminator for the structured-details `reason` field
82 /// on the `INVALID_TITLE` wire envelope. Each surface (MCP, CLI)
83 /// reads this when building the response payload.
84 pub fn reason(&self) -> &'static str {
85 match self {
86 SlugError::IdTooLong { .. } => "id_too_long",
87 SlugError::TitleEmpty { .. } => "empty",
88 SlugError::TitleHasControlChars { .. } => "control_chars",
89 }
90 }
91}
92
93/// The separator between mem and entity path in IDs.
94/// Build an EntityId from mem and title.
95pub fn build_id(mem: &str, title: &str) -> Result<EntityId, SlugError> {
96 let slug = title_to_slug(title)?;
97 let id = EntityId::new(mem, &slug);
98 enforce_id_length(id.as_ref())?;
99 Ok(id)
100}
101
102/// Reject ids whose Unicode scalar length exceeds
103/// [`ENTITY_ID_MAX_LEN`]. Shared by [`build_id`] and the engine's
104/// `create_entity` / `rename_entity` paths so the write side never
105/// produces an id the read side would refuse. The cap is on the
106/// composed `<mem>--<slug>` id (which is also the filename), so the
107/// error echoes the id itself — the `reason`, the echoed `input`, and
108/// the reported `length` all describe the id, not the title.
109pub fn enforce_id_length(id: &str) -> Result<(), SlugError> {
110 if id.chars().count() > ENTITY_ID_MAX_LEN {
111 return Err(SlugError::IdTooLong {
112 input: id.to_string(),
113 length: id.chars().count(),
114 max: ENTITY_ID_MAX_LEN,
115 });
116 }
117 Ok(())
118}
119
120/// Convert a title string to a kebab-case slug.
121///
122/// Pipeline:
123///
124/// 1. **NFC-normalize** so combining sequences fold into precomposed
125/// forms (`Café` written NFD becomes `Café` written NFC). One
126/// canonical surface form keeps slug equality byte-stable across
127/// NFD-storing filesystems (older HFS+) and NFC-default ones
128/// (APFS, ext4, NTFS).
129/// 2. **Lowercase** via Unicode default case-folding — correct for
130/// Latin / Cyrillic / Greek / Armenian; no-op for case-less
131/// scripts (CJK, Arabic, Hebrew, Devanagari, Thai, etc.).
132/// 3. **Whitespace → hyphen**.
133/// 4. **Filter to `is_alphanumeric() || '-'`** — Unicode alphanumeric,
134/// not ASCII. Keeps every Latin and non-Latin letter or digit;
135/// drops combining marks, punctuation, symbols, emoji, and the
136/// reserved `--` / `:` separators by construction.
137/// 5. **Collapse hyphen runs, trim**.
138///
139/// Always returns `Ok(...)`. When the filter leaves the slug empty
140/// (all-emoji titles, all-punctuation, all-symbol titles), the slug
141/// degrades to a deterministic short hash of the title
142/// (`entity-<8-hex>`) rather than failing. Titles that are already
143/// slug-form — case-less scripts (`知識グラフ`) and lowercase
144/// single-token Latin (`garden`) — produce slug == title, so
145/// Obsidian-style `[[<title>]]` authoring round-trips without lookup
146/// for exactly those titles; any other title (a capital, a space:
147/// `Knowledge Graph`) derives a different slug, and the strict
148/// wiki-link decoder below refuses the natural form as a link target
149/// — such entities are linked by slug (`[[knowledge-graph]]`).
150pub fn title_to_slug(title: &str) -> Result<String, SlugError> {
151 let normalized: String = title.nfc().collect();
152 let slug: String = normalized
153 .chars()
154 .flat_map(|c| c.to_lowercase())
155 .map(|c| if c.is_whitespace() { '-' } else { c })
156 .filter(|c| c.is_alphanumeric() || *c == '-')
157 .collect::<String>()
158 .split('-')
159 .filter(|s| !s.is_empty())
160 .collect::<Vec<_>>()
161 .join("-");
162 if slug.is_empty() {
163 return Ok(format!("entity-{}", short_hash(title)));
164 }
165 Ok(slug)
166}
167
168/// The accepted title grammar, stated as a rule. THE single sentence
169/// every surface that documents titles carries: the CLI's
170/// create/rename help embeds it at build time, the MCP
171/// `memstead_create` / `memstead_rename` descriptions contain it
172/// verbatim (a tool-surface test asserts the containment), and the
173/// handbook quotes it naming this constant as its source. A
174/// conformance test in this module asserts
175/// [`validate_and_derive_slug`]'s behaviour matches the sentence's
176/// claim — so neither the prose nor the validator can drift alone.
177///
178/// The sentence's two claims, executable:
179///
180/// ```
181/// use memstead_base::entity::id::validate_and_derive_slug;
182///
183/// // "control characters such as tab/newline are rejected"
184/// assert!(validate_and_derive_slug("two\nlines").is_err());
185///
186/// // "characters outside Unicode alphanumerics, whitespace, and
187/// // hyphen are dropped from the derived slug" — and reported.
188/// let d = validate_and_derive_slug("The Gate's Rule — v2").unwrap();
189/// assert_eq!(d.slug, "the-gates-rule-v2");
190/// assert_eq!(d.dropped_chars, vec!['\'', '—']);
191/// ```
192pub 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";
193
194/// A strict-gate derivation result: the slug plus the distinct title
195/// characters (source order, post NFC + case-fold) the pipeline
196/// dropped on the way. `dropped_chars` non-empty means the title and
197/// its id diverge beyond case/whitespace — the mutation surfaces it
198/// as the typed `TITLE_CHARS_DROPPED_FROM_SLUG` warning so the
199/// divergence stays visible without being fatal.
200#[derive(Debug, Clone, PartialEq, Eq)]
201pub struct SlugDerivation {
202 pub slug: String,
203 pub dropped_chars: Vec<char>,
204}
205
206/// Strict slug derivation for mutation entry (`memstead_create`,
207/// `memstead_rename`). Runs the same pipeline as [`title_to_slug`] —
208/// byte-identical slugs for every title — but refuses the residual
209/// cases the permissive variant tolerates:
210///
211/// 1. **Control characters.** They would survive verbatim into the
212/// stored `# H1` and split it across lines. Returns
213/// [`SlugError::TitleHasControlChars`].
214/// 2. **Empty / collapses-to-empty.** Empty input, whitespace-only,
215/// hyphen-only, or all-dropped input — anything that would force
216/// the loader-path hash fallback. Returns [`SlugError::TitleEmpty`].
217///
218/// Any other character is admitted: the title is display text, stored
219/// verbatim, and characters outside the slug alphabet are dropped from
220/// the derived slug and reported in
221/// [`SlugDerivation::dropped_chars`] ([`TITLE_GRAMMAR_RULE`]).
222///
223/// Loader paths continue to call [`title_to_slug`] so pre-gate
224/// entities created with the old permissive pipeline remain
225/// readable — only mutation entry runs this strict gate.
226///
227/// ```
228/// use memstead_base::entity::id::{SlugError, validate_and_derive_slug};
229///
230/// // The happy path: Unicode-aware kebab-case, divergence reported.
231/// let d = validate_and_derive_slug("Knowledge Graph!").unwrap();
232/// assert_eq!(d.slug, "knowledge-graph");
233/// assert_eq!(d.dropped_chars, vec!['!']);
234///
235/// // Refusal 1: control characters.
236/// assert!(matches!(
237/// validate_and_derive_slug("tab\there"),
238/// Err(SlugError::TitleHasControlChars { .. })
239/// ));
240///
241/// // Refusal 2: a title whose slug collapses to empty.
242/// assert!(matches!(
243/// validate_and_derive_slug("!!!"),
244/// Err(SlugError::TitleEmpty { .. })
245/// ));
246/// ```
247pub fn validate_and_derive_slug(title: &str) -> Result<SlugDerivation, SlugError> {
248 let normalized: String = title.nfc().collect();
249 let case_folded: String = normalized.chars().flat_map(|c| c.to_lowercase()).collect();
250
251 // Control characters (newline, tab, other C0/C1) are Unicode
252 // whitespace, so the slug pipeline below would fold them to hyphens
253 // and accept the title — but they survive into the stored `# H1`,
254 // splitting it across lines and truncating every read of the title.
255 // Refuse them before the slug derivation.
256 let mut control_chars: Vec<char> = Vec::new();
257 for c in case_folded.chars() {
258 if c.is_control() && !control_chars.contains(&c) {
259 control_chars.push(c);
260 }
261 }
262 if !control_chars.is_empty() {
263 let proposed = title_to_slug(title).unwrap_or_default();
264 return Err(SlugError::TitleHasControlChars {
265 input: title.to_string(),
266 control_chars,
267 proposed_slug: proposed,
268 });
269 }
270
271 // Characters outside the slug alphabet are dropped from the id —
272 // recorded, not refused: the title is display text, the slug is
273 // the sanitised identifier, and the divergence rides back to the
274 // caller as a typed warning.
275 let mut dropped_chars: Vec<char> = Vec::new();
276 for c in case_folded.chars() {
277 if c.is_whitespace() || c == '-' || c.is_alphanumeric() {
278 continue;
279 }
280 if !dropped_chars.contains(&c) {
281 dropped_chars.push(c);
282 }
283 }
284
285 let slug: String = case_folded
286 .chars()
287 .filter(|c| c.is_whitespace() || *c == '-' || c.is_alphanumeric())
288 .map(|c| if c.is_whitespace() { '-' } else { c })
289 .collect::<String>()
290 .split('-')
291 .filter(|s| !s.is_empty())
292 .collect::<Vec<_>>()
293 .join("-");
294
295 if slug.is_empty() {
296 return Err(SlugError::TitleEmpty {
297 input: title.to_string(),
298 });
299 }
300
301 Ok(SlugDerivation {
302 slug,
303 dropped_chars,
304 })
305}
306
307/// Deterministic 8-char hex digest used as the fallback slug when
308/// the title contains no Unicode alphanumeric characters (the
309/// residual case of [`title_to_slug`]'s pipeline). 32 bits is
310/// plenty for collision-resistance inside a single mem; the
311/// fallback only fires for titles that contain no
312/// agent-meaningful characters anyway, so the opaque form is
313/// acceptable.
314fn short_hash(input: &str) -> String {
315 use sha2::{Digest, Sha256};
316 let digest = Sha256::digest(input.as_bytes());
317 format!(
318 "{:02x}{:02x}{:02x}{:02x}",
319 digest[0], digest[1], digest[2], digest[3]
320 )
321}
322
323/// Convert a relative file path to a mem-prefixed entity ID.
324///
325/// `file_path_to_id("architecture/result.md", "specs")` → `specs--architecture/result`
326pub fn file_path_to_id(path: &str, mem: &str) -> EntityId {
327 let stripped = path.strip_suffix(".md").unwrap_or(path);
328 EntityId::new(mem, stripped)
329}
330
331/// Strict wiki-link grammar refusal. Returned by [`wiki_link_to_id`]
332/// when the input between `[[...]]` (after alias / `.md` strip) does
333/// not resolve to a slug-form `EntityId`. Two variants matching the
334/// two grammars a wiki-link target carries:
335///
336/// - [`Self::InvalidMemName`] — Tier-2 prefix `[[mem:slug]]`'s
337/// mem name fails [`validate_mem_name_grammar`]. Recovery is
338/// manual: mem names are fixed identifiers in the workspace, not
339/// free-form text the agent can slugify.
340/// - [`Self::InvalidTarget`] — the slug-form path fails
341/// [`validate_id_path_grammar`]. Carries the
342/// [`title_to_slug`]-derived suggestion (omitted when the input
343/// has no meaningful slug equivalent — empty, all-punctuation,
344/// all-emoji).
345#[derive(Debug, thiserror::Error, Clone)]
346pub enum WikiLinkError {
347 #[error("mem prefix '{raw}' is not a valid mem name: {reason}")]
348 InvalidMemName { raw: String, reason: String },
349 #[error("wiki-link target '{raw}' is not slug-form: {reason}")]
350 InvalidTarget {
351 raw: String,
352 suggested: Option<String>,
353 reason: String,
354 },
355}
356
357/// Compute the [`title_to_slug`]-derived suggestion for a malformed
358/// wiki-link target. Returns `None` when the slug pipeline produces
359/// either an empty result or the deterministic hash fallback
360/// (`entity-<8hex>`) — both signal that the input has no canonical
361/// form the agent can mechanically lift into a retry.
362fn wiki_link_suggestion(raw: &str) -> Option<String> {
363 let derived = title_to_slug(raw).ok()?;
364 if derived.is_empty() || derived.starts_with("entity-") {
365 return None;
366 }
367 validate_id_path_grammar(&derived)
368 .is_ok()
369 .then_some(derived)
370}
371
372/// Convert a wiki-link target to a mem-prefixed entity ID, refusing
373/// non-slug-form inputs.
374///
375/// Recognises three grammars:
376/// - **Tier 0** `[[<mem>--<slug>]]` — cross-mem dash-form,
377/// symmetric with every engine-emitted ID: body wiki-links accept
378/// the canonical `<mem>--<slug>` form the engine writes elsewhere
379/// so an agent can author the same grammar in both directions.
380/// `<mem>` must match the single-segment mem-name grammar
381/// (`[a-z0-9-]+`, no `/`); hierarchical mem names stay on the
382/// Tier-2 colon-form. Cross-mem routing is policy-gated downstream in
383/// the alias-synthesis pass (same code path that already gates
384/// body-link → REFERENCES emission).
385/// - **Tier 1** `[[slug]]` or `[[a/b/c]]` — same-mem, resolves to
386/// `<current_mem>--<slug>`.
387/// - **Tier 2** `[[leaf:slug]]` — cross-mem, same mem-repo, resolves
388/// to `<leaf>--<slug>`. Hierarchical paths are first-class: the
389/// prefix accepts the full `team/sub-mem` form, so
390/// `[[team/sub-mem:auth-service]]` resolves to
391/// `team/sub-mem--auth-service`. Tier-1 with a
392/// hierarchical-mem dash-prefix (`[[team/sub-mem--auth-service]]`)
393/// remains unsupported — that combination is genuinely ambiguous
394/// between a cross-mem reference into a hierarchical mem and a
395/// same-mem entity at a hierarchical slug. Operators authoring
396/// such references must use the colon Tier-2 form.
397///
398/// Strips `[[` / `]]`, Obsidian alias (`|display`), `../` prefixes, `.md`
399/// suffix, and a redundant leading `<current_mem>--` (so an agent that
400/// writes the canonical fully-qualified id `[[mem--slug]]` produces the
401/// same `EntityId` as the bare-slug form `[[slug]]` instead of doubly-
402/// prefixing into `mem--mem--slug`).
403///
404/// Strictness: any input whose Tier-2 prefix fails
405/// [`validate_mem_name_grammar`] or whose resolved slug fails
406/// [`validate_id_path_grammar`] refuses with [`WikiLinkError`]. There is
407/// no permissive form that constructs an `EntityId` from any character
408/// sequence between the brackets — callers
409/// (`extract_inline_links`, the relate path's body scanners)
410/// propagate the refusal so an agent's `[[Knowledge Graph]]` body
411/// link can no longer land a malformed auto-stub. Read-side scanners
412/// that must tolerate pre-strict on-disk drift use
413/// [`wiki_link_to_id_lenient`].
414///
415/// Hierarchical-dash ambiguity: the Tier-1 fallback refuses inputs whose post-
416/// self-prefix-strip slug contains BOTH `/` and `--`
417/// (`[[team/sub-mem--target]]`). The combination is grammatically
418/// ambiguous between a cross-mem reference into a hierarchical mem
419/// and a same-mem entity at a hierarchical slug; the refusal carries
420/// the canonical colon form (`team/sub-mem:target`) as `suggested`.
421pub fn wiki_link_to_id(link: &str, current_mem: &str) -> Result<EntityId, WikiLinkError> {
422 let stripped = strip_wiki_link_decorations(link);
423
424 if !stripped.contains("::")
425 && let Some(colon_idx) = stripped.find(':')
426 {
427 let (prefix, rest) = stripped.split_at(colon_idx);
428 let slug_part = &rest[1..];
429 if !prefix.is_empty() && !slug_part.is_empty() {
430 if let Err(reason) = validate_mem_name_grammar(prefix) {
431 return Err(WikiLinkError::InvalidMemName {
432 raw: prefix.to_string(),
433 reason,
434 });
435 }
436 if let Err(reason) = validate_id_path_grammar(slug_part) {
437 let suggested = wiki_link_suggestion(slug_part).map(|s| format!("{prefix}:{s}"));
438 return Err(WikiLinkError::InvalidTarget {
439 raw: stripped.to_string(),
440 suggested,
441 reason,
442 });
443 }
444 return Ok(EntityId::new(prefix, slug_part));
445 }
446 }
447
448 // Tier 0 — cross-mem dash form `<mem>--<slug>`. Symmetric
449 // with every engine-emitted ID. Recognises only
450 // single-segment mem names (no `/` in the prefix); the
451 // hierarchical-mem dash form is grammatically ambiguous (see
452 // the dash/slash refusal further down) and stays on the colon
453 // Tier-2 form. Routes to the named mem even when it differs
454 // from `current_mem` — the cross-mem policy gate fires in
455 // the alias-synthesis pass, not here.
456 if let Some(dash_idx) = stripped.find("--") {
457 let prefix = &stripped[..dash_idx];
458 let suffix = &stripped[dash_idx + 2..];
459 if !prefix.is_empty()
460 && !suffix.is_empty()
461 && !prefix.contains('/')
462 && validate_mem_name_grammar(prefix).is_ok()
463 && validate_id_path_grammar(suffix).is_ok()
464 {
465 return Ok(EntityId::new(prefix, suffix));
466 }
467 }
468
469 let slug = if !current_mem.is_empty() {
470 let self_prefix = format!("{current_mem}--");
471 stripped
472 .strip_prefix(self_prefix.as_str())
473 .unwrap_or(&stripped)
474 } else {
475 &stripped
476 };
477 // A slug carrying BOTH `/` and `--` is grammatically ambiguous —
478 // it could be a cross-mem reference into a hierarchical mem
479 // (`team/sub-mem--target` → mem `team/sub-mem`, slug `target`)
480 // or a same-mem entity at a hierarchical slug that happens to
481 // contain `--`. The docstring above pins the canonical disambiguation
482 // (colon-form for cross-mem) but the dash form silently collapsed
483 // to the same-mem interpretation pre-fix, landing phantom stubs
484 // for any agent writing `[[team/sub-mem--target]]` in body text.
485 // Refuse and surface the colon-form as the recovery hint.
486 if let Some(dash_idx) = slug.find("--")
487 && slug[..dash_idx].contains('/')
488 {
489 let prefix = &slug[..dash_idx];
490 let suffix = &slug[dash_idx + 2..];
491 let cross_mem_form = format!("{prefix}:{suffix}");
492 let same_mem_form = if current_mem.is_empty() {
493 format!("<current-mem>:{slug}")
494 } else {
495 format!("{current_mem}:{slug}")
496 };
497 return Err(WikiLinkError::InvalidTarget {
498 raw: stripped.to_string(),
499 suggested: Some(cross_mem_form),
500 reason: format!(
501 "wiki-link target contains both '/' and '--', which is ambiguous \
502 between a cross-mem reference into a hierarchical mem and a \
503 same-mem entity at a hierarchical slug; use the colon form \
504 '[[{prefix}:{suffix}]]' for a cross-mem reference, or \
505 '[[{same_mem_form}]]' for a same-mem entity whose slug \
506 contains '--'"
507 ),
508 });
509 }
510 if let Err(reason) = validate_id_path_grammar(slug) {
511 return Err(WikiLinkError::InvalidTarget {
512 raw: stripped.to_string(),
513 suggested: wiki_link_suggestion(slug),
514 reason,
515 });
516 }
517 Ok(EntityId::new(current_mem, slug))
518}
519
520/// Permissive wiki-link decoder for read-side scanners that must
521/// tolerate pre-strict-gate on-disk drift (e.g. dangling-link
522/// reporters, body-link scanners on stored entities, archive readers
523/// for non-canonical sources). Returns an `EntityId` even for
524/// non-slug-form input — non-conformant chars flow through
525/// unchanged. Mutation paths MUST
526/// NOT use this helper; they use [`wiki_link_to_id`] and propagate
527/// the typed refusal.
528pub fn wiki_link_to_id_lenient(link: &str, current_mem: &str) -> EntityId {
529 // Strip decorations and trim to a FIXPOINT: each pass can expose
530 // work for another — an alias/anchor cut exposes trailing
531 // whitespace (`foo |label` → `foo `), and trimming that whitespace
532 // can expose a `.md` suffix the pass could not see (`x.md\r` →
533 // `x.md` → `x`; fuzz finding, corpus member `crash-b256aad3…`).
534 // The tolerant path must land on ids the generator round-trips
535 // (parse→generate is a fixpoint after one round), so it normalises
536 // until nothing changes. The loop terminates because every pass
537 // only ever shortens the string. Deliberately NOT in the shared
538 // helper: the strict decoder runs one pass and its grammar gate
539 // still refuses the leftover shapes.
540 let mut stripped = strip_wiki_link_decorations(link);
541 loop {
542 let next = strip_wiki_link_decorations(stripped.trim_end());
543 if next == stripped {
544 break;
545 }
546 stripped = next;
547 }
548 let stripped = stripped.trim_end();
549
550 if !stripped.contains("::")
551 && let Some(colon_idx) = stripped.find(':')
552 {
553 let (prefix, rest) = stripped.split_at(colon_idx);
554 let slug_part = &rest[1..];
555 if !prefix.is_empty() && !slug_part.is_empty() {
556 return EntityId::new(prefix, slug_part);
557 }
558 }
559
560 // Tier 0 — cross-mem dash form. Read-side mirror of the strict
561 // decoder's recognition so dangling-link reports and graph
562 // inspectors interpret on-disk `[[other--target]]` the same way
563 // the mutation gate writes it. Pre-strict drift on older entities
564 // keeps the bare-slug fallback below for
565 // shapes the tier-0 doesn't admit (empty prefix, hierarchical
566 // prefix, malformed slug).
567 if let Some(dash_idx) = stripped.find("--") {
568 let prefix = &stripped[..dash_idx];
569 let suffix = &stripped[dash_idx + 2..];
570 if !prefix.is_empty()
571 && !suffix.is_empty()
572 && !prefix.contains('/')
573 && validate_mem_name_grammar(prefix).is_ok()
574 && validate_id_path_grammar(suffix).is_ok()
575 {
576 return EntityId::new(prefix, suffix);
577 }
578 }
579
580 let slug = if !current_mem.is_empty() {
581 let self_prefix = format!("{current_mem}--");
582 stripped
583 .strip_prefix(self_prefix.as_str())
584 .unwrap_or(stripped)
585 } else {
586 stripped
587 };
588 EntityId::new(current_mem, slug)
589}
590
591/// Strip `[[`/`]]`, the Obsidian alias suffix `|display`, the section
592/// anchor `#section` (plus any trailing `#sub` etc — stripped from the
593/// first `#` onward), leading `../` segments, and the trailing `.md`
594/// suffix from a raw wiki-link token. Shared by the strict and
595/// lenient decoders so the pre-grammar-gate textual normalisation is
596/// byte-equivalent on both paths.
597///
598/// `#anchor` strip: Obsidian-style section anchors are display-only at
599/// the graph layer; the engine has no semantic use for them. Strip
600/// from the first `#` onward so multi-anchor forms like
601/// `target#a#b` collapse to `target` in one pass. Ordered after the
602/// `|alias` strip so `target#section|display` correctly drops both
603/// (the alias strip drops `|display` first, leaving `target#section`;
604/// the anchor strip then drops `#section`).
605pub(crate) fn strip_wiki_link_decorations(link: &str) -> String {
606 let cleaned = link.trim_start_matches("[[").trim_end_matches("]]").trim();
607 let target = match cleaned.find('|') {
608 Some(i) => &cleaned[..i],
609 None => cleaned,
610 };
611 let target_no_anchor = match target.find('#') {
612 Some(i) => &target[..i],
613 None => target,
614 };
615 let target_no_dotdot = target_no_anchor.trim_start_matches("../");
616 target_no_dotdot
617 .strip_suffix(".md")
618 .unwrap_or(target_no_dotdot)
619 .to_string()
620}
621
622/// Compute the file path for an entity given its ID and base directory.
623/// The path is relative to the mem directory.
624///
625/// `specs--architecture/result-entity` → `architecture/result-entity.md`
626pub fn id_to_file_path(id: &EntityId) -> String {
627 format!("{}.md", id.path())
628}
629
630/// Validate that an `EntityId`'s path matches the wiki-link grammar
631/// (`^[\p{Ll}\p{Lo}\p{Lm}\p{N}-]+(/[\p{Ll}\p{Lo}\p{Lm}\p{N}-]+)*$`).
632/// Same regex the strict ingress validator applies to inline
633/// `[[...]]` targets — keeping the two gates aligned ensures the
634/// relate-target path doesn't admit ids that would fail an in-body
635/// wiki-link parse.
636///
637/// Accepted character classes match what [`title_to_slug`] produces:
638/// Unicode lowercase letters (`\p{Ll}`), case-less letters
639/// (`\p{Lo}` — CJK, Arabic, Hebrew, Devanagari, Thai, …), modifier
640/// letters (`\p{Lm}` — e.g. Japanese prolonged-sound mark `ー`),
641/// any Unicode numeric (`\p{N}`), and hyphen. Mem names stay
642/// ASCII — see [`validate_mem_name_grammar`].
643///
644/// Returns the original path on success, an error message on failure.
645/// Callers wrap the failure into a typed envelope (e.g.
646/// `INVALID_ENTITY_ID`).
647pub fn validate_id_path_grammar(path: &str) -> Result<&str, String> {
648 use std::sync::OnceLock;
649 static RE: OnceLock<regex::Regex> = OnceLock::new();
650 let re = RE.get_or_init(|| {
651 regex::Regex::new(
652 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}-]+)*$",
653 )
654 .unwrap()
655 });
656 if re.is_match(path) {
657 Ok(path)
658 } else {
659 Err(format!(
660 "id path '{path}' does not match the wiki-link grammar — \
661 entity slugs must be lowercase Unicode letters / digits / \
662 hyphens, with path segments separated by '/'"
663 ))
664 }
665}
666
667/// Validate a mem name (left side of `--`). Hierarchical paths are
668/// first-class: mem names accept `<segment>(/<segment>)*` where each
669/// segment matches the single-segment rule (`[a-z0-9-]+`). Leading slashes,
670/// trailing slashes, double slashes, and any character outside the
671/// allowed segment alphabet are explicit refusals.
672///
673/// Flat (single-segment) names work unchanged — the
674/// regex's `(/<segment>)*` tail matches zero or more times. The
675/// storage representation uses the full path for the
676/// `__MEMSTEAD` config blob (`__MEMSTEAD:mems/<path>/config.json`), the
677/// branch ref (`refs/heads/<path>`), and the in-memory router key.
678pub fn validate_mem_name_grammar(mem: &str) -> Result<&str, String> {
679 use std::sync::OnceLock;
680 static RE: OnceLock<regex::Regex> = OnceLock::new();
681 let re = RE.get_or_init(|| regex::Regex::new(r"^[a-z0-9-]+(/[a-z0-9-]+)*$").unwrap());
682 if re.is_match(mem) {
683 Ok(mem)
684 } else {
685 Err(format!(
686 "mem name '{mem}' must match ^[a-z0-9-]+(/[a-z0-9-]+)*$ \
687 (lowercase ASCII / digits / hyphens, optionally segmented \
688 by '/' for hierarchical layouts; no leading, trailing, or \
689 double slashes)"
690 ))
691 }
692}
693
694/// Validate relationship type. Input is case-insensitive and canonicalised
695/// to uppercase; only ASCII letters and underscores are permitted.
696pub fn validate_rel_type(rel_type: &str) -> Result<String, String> {
697 let cleaned = rel_type.to_uppercase();
698 if cleaned.chars().all(|c| c.is_ascii_uppercase() || c == '_') && !cleaned.is_empty() {
699 Ok(cleaned)
700 } else {
701 Err(format!(
702 "Invalid relationship type: \"{rel_type}\". Only ASCII letters and underscores allowed (input is canonicalised to uppercase)."
703 ))
704 }
705}
706
707#[cfg(test)]
708mod tests;