Skip to main content

khive_types/
entity_type.rs

1//! EntityTypeRegistry — validates and normalises `(EntityKind, entity_type)` pairs.
2//!
3//! Canonical, dependency-light home for the closed entity-subtype taxonomy
4//! (#571): both KG create validation and schedule replay validation resolve
5//! against this single registry instead of maintaining separate copies.
6
7use alloc::collections::BTreeMap;
8use alloc::format;
9use alloc::string::{String, ToString};
10use alloc::vec::Vec;
11use core::fmt;
12
13use crate::entity::EntityKind;
14
15/// Normalise a raw `entity_type` string to canonical snake_case.
16///
17/// Pipeline: trim → lowercase → runs of separators (space, hyphen, underscore)
18/// collapsed to a single `_` → leading/trailing `_` stripped.
19///
20/// This implements the ADR-001:106 write-time normalisation step that precedes
21/// alias resolution. `pub` (not `pub(crate)`) so callers outside this crate —
22/// e.g. `khive-pack-kg`'s alias-substitution reporting — can compare a raw
23/// value against this SAME cosmetic normalisation instead of maintaining a
24/// separate, drift-prone copy of the rule.
25pub fn to_snake_case(s: &str) -> String {
26    let mut out = String::with_capacity(s.len());
27    let mut prev_sep = true; // treat start as separator so leading _ are stripped
28    for ch in s.chars() {
29        if ch == ' ' || ch == '-' || ch == '_' {
30            if !prev_sep && !out.is_empty() {
31                out.push('_');
32                prev_sep = true;
33            }
34        } else {
35            out.push(ch.to_ascii_lowercase());
36            prev_sep = false;
37        }
38    }
39    if out.ends_with('_') {
40        out.pop();
41    }
42    out
43}
44
45/// One entry in the registry: a canonical subtype name for a specific kind,
46/// together with any accepted aliases.
47#[derive(Clone, Debug)]
48pub struct EntityTypeDef {
49    /// The entity kind this subtype belongs to.
50    pub kind: EntityKind,
51    /// Canonical name that is written to the DB.
52    pub type_name: &'static str,
53    /// Alternative spellings that are accepted at the wire level but
54    /// normalised to `type_name` before storage.
55    pub aliases: &'static [&'static str],
56}
57
58/// Static table of built-in subtypes (non-exhaustive; packs may extend).
59static BUILTIN_DEFS: &[EntityTypeDef] = &[
60    // ── Document ────────────────────────────────────────────────────────────
61    EntityTypeDef {
62        kind: EntityKind::Document,
63        type_name: "paper",
64        aliases: &["preprint", "article"],
65    },
66    EntityTypeDef {
67        kind: EntityKind::Document,
68        type_name: "report",
69        aliases: &[],
70    },
71    EntityTypeDef {
72        kind: EntityKind::Document,
73        type_name: "blog_post",
74        aliases: &["blog"],
75    },
76    EntityTypeDef {
77        kind: EntityKind::Document,
78        type_name: "book",
79        aliases: &[],
80    },
81    EntityTypeDef {
82        kind: EntityKind::Document,
83        type_name: "specification",
84        aliases: &["spec"],
85    },
86    EntityTypeDef {
87        kind: EntityKind::Document,
88        type_name: "documentation",
89        aliases: &["docs"],
90    },
91    EntityTypeDef {
92        kind: EntityKind::Document,
93        type_name: "thesis",
94        aliases: &[],
95    },
96    EntityTypeDef {
97        kind: EntityKind::Document,
98        type_name: "page",
99        aliases: &["web_page"],
100    },
101    // ADR-191: any fetched body other than an HTML page — robots.txt, a
102    // sitemap, a feed, a JSON body, a PDF, an alternate rendering served at
103    // its own URL.
104    EntityTypeDef {
105        kind: EntityKind::Document,
106        type_name: "resource",
107        aliases: &[],
108    },
109    EntityTypeDef {
110        kind: EntityKind::Document,
111        type_name: "research_report",
112        aliases: &[],
113    },
114    // ── Concept ─────────────────────────────────────────────────────────────
115    EntityTypeDef {
116        kind: EntityKind::Concept,
117        type_name: "algorithm",
118        aliases: &["algo"],
119    },
120    // ── Formal math ─────────────────────────────────────────────────────────
121    EntityTypeDef {
122        kind: EntityKind::Concept,
123        type_name: "theorem",
124        aliases: &["lemma", "proposition", "corollary"],
125    },
126    EntityTypeDef {
127        kind: EntityKind::Concept,
128        type_name: "definition",
129        aliases: &["def"],
130    },
131    EntityTypeDef {
132        kind: EntityKind::Concept,
133        type_name: "structure",
134        aliases: &["inductive", "struct", "class"],
135    },
136    EntityTypeDef {
137        kind: EntityKind::Concept,
138        type_name: "instance",
139        aliases: &[],
140    },
141    EntityTypeDef {
142        kind: EntityKind::Concept,
143        type_name: "axiom",
144        aliases: &[],
145    },
146    EntityTypeDef {
147        kind: EntityKind::Concept,
148        type_name: "goal",
149        aliases: &["proof_goal"],
150    },
151    EntityTypeDef {
152        kind: EntityKind::Concept,
153        type_name: "technique",
154        aliases: &[],
155    },
156    EntityTypeDef {
157        kind: EntityKind::Concept,
158        type_name: "architecture",
159        aliases: &["arch"],
160    },
161    EntityTypeDef {
162        kind: EntityKind::Concept,
163        // "model" is the alias; canonical name is "model_family"
164        // to distinguish from a Dataset or Artifact trained model instance.
165        type_name: "model_family",
166        aliases: &["model"],
167    },
168    EntityTypeDef {
169        kind: EntityKind::Concept,
170        type_name: "theory",
171        aliases: &[],
172    },
173    EntityTypeDef {
174        kind: EntityKind::Concept,
175        type_name: "research_gap",
176        aliases: &["gap"],
177    },
178    EntityTypeDef {
179        kind: EntityKind::Concept,
180        type_name: "design_pattern",
181        aliases: &["pattern"],
182    },
183    EntityTypeDef {
184        kind: EntityKind::Concept,
185        type_name: "mathematical_operation",
186        aliases: &["math_op"],
187    },
188    EntityTypeDef {
189        kind: EntityKind::Concept,
190        type_name: "metric",
191        aliases: &[],
192    },
193    EntityTypeDef {
194        kind: EntityKind::Concept,
195        type_name: "objective",
196        aliases: &["loss"],
197    },
198    // ── Code (ADR-085) ──────────────────────────────────────────────────────
199    // "struct" and "class" are not registered as aliases here: formal-math
200    // "structure" already owns them (see above), and ADR-085 requires
201    // ingesters to write the canonical code tokens instead.
202    EntityTypeDef {
203        kind: EntityKind::Concept,
204        type_name: "module",
205        aliases: &["mod", "namespace"],
206    },
207    EntityTypeDef {
208        kind: EntityKind::Concept,
209        type_name: "function",
210        aliases: &["fn", "func", "method"],
211    },
212    EntityTypeDef {
213        kind: EntityKind::Concept,
214        type_name: "datatype",
215        aliases: &["enum", "record", "type_alias"],
216    },
217    EntityTypeDef {
218        kind: EntityKind::Concept,
219        type_name: "interface",
220        aliases: &["trait", "protocol"],
221    },
222    // ── Dataset ──────────────────────────────────────────────────────────────
223    // benchmark belongs to Dataset, not Concept (it evaluates models, it is not itself a concept).
224    EntityTypeDef {
225        kind: EntityKind::Dataset,
226        type_name: "benchmark",
227        aliases: &[],
228    },
229    EntityTypeDef {
230        kind: EntityKind::Dataset,
231        type_name: "corpus",
232        aliases: &[],
233    },
234    EntityTypeDef {
235        kind: EntityKind::Dataset,
236        type_name: "training_set",
237        aliases: &["train_set"],
238    },
239    EntityTypeDef {
240        kind: EntityKind::Dataset,
241        type_name: "evaluation_set",
242        aliases: &["eval_set"],
243    },
244    EntityTypeDef {
245        kind: EntityKind::Dataset,
246        type_name: "test_set",
247        aliases: &[],
248    },
249    EntityTypeDef {
250        kind: EntityKind::Dataset,
251        type_name: "synthetic_dataset",
252        aliases: &["synthetic"],
253    },
254    // ── Project ─────────────────────────────────────────────────────────────
255    // Project subtypes: library, framework, tool, application, repository.
256    // "service" and "svc" are omitted — EntityKind::Service handles running
257    // instances; a service codebase repo is Project + application or tool.
258    EntityTypeDef {
259        kind: EntityKind::Project,
260        type_name: "library",
261        aliases: &["lib"],
262    },
263    EntityTypeDef {
264        kind: EntityKind::Project,
265        type_name: "framework",
266        aliases: &[],
267    },
268    EntityTypeDef {
269        kind: EntityKind::Project,
270        type_name: "tool",
271        aliases: &[],
272    },
273    EntityTypeDef {
274        kind: EntityKind::Project,
275        type_name: "application",
276        aliases: &["app"],
277    },
278    EntityTypeDef {
279        kind: EntityKind::Project,
280        type_name: "repository",
281        aliases: &["repo"],
282    },
283    // ── Org ──────────────────────────────────────────────────────────────────
284    EntityTypeDef {
285        kind: EntityKind::Org,
286        type_name: "academic_institution",
287        aliases: &["university", "uni"],
288    },
289    EntityTypeDef {
290        kind: EntityKind::Org,
291        type_name: "company",
292        aliases: &[],
293    },
294    EntityTypeDef {
295        kind: EntityKind::Org,
296        type_name: "research_lab",
297        aliases: &["lab"],
298    },
299    EntityTypeDef {
300        kind: EntityKind::Org,
301        type_name: "nonprofit",
302        aliases: &[],
303    },
304    EntityTypeDef {
305        kind: EntityKind::Org,
306        type_name: "government_agency",
307        aliases: &["gov_agency"],
308    },
309    EntityTypeDef {
310        kind: EntityKind::Org,
311        type_name: "consortium",
312        aliases: &[],
313    },
314    EntityTypeDef {
315        kind: EntityKind::Org,
316        type_name: "standards_body",
317        aliases: &[],
318    },
319    // ── Artifact ─────────────────────────────────────────────────────────────
320    EntityTypeDef {
321        kind: EntityKind::Artifact,
322        type_name: "checkpoint",
323        aliases: &["ckpt"],
324    },
325    EntityTypeDef {
326        kind: EntityKind::Artifact,
327        type_name: "snapshot",
328        aliases: &[],
329    },
330    EntityTypeDef {
331        kind: EntityKind::Artifact,
332        type_name: "export",
333        aliases: &[],
334    },
335    EntityTypeDef {
336        kind: EntityKind::Artifact,
337        type_name: "embedding_index",
338        aliases: &["embed_index"],
339    },
340    EntityTypeDef {
341        kind: EntityKind::Artifact,
342        type_name: "state_bundle",
343        aliases: &[],
344    },
345    EntityTypeDef {
346        kind: EntityKind::Artifact,
347        type_name: "profile",
348        aliases: &[],
349    },
350    // ── Service ──────────────────────────────────────────────────────────────
351    // Service subtypes: inference_engine, retrieval_engine,
352    // embedding_engine, api, database, search_engine, mcp_server, site.
353    EntityTypeDef {
354        kind: EntityKind::Service,
355        type_name: "inference_engine",
356        aliases: &[],
357    },
358    EntityTypeDef {
359        kind: EntityKind::Service,
360        type_name: "retrieval_engine",
361        aliases: &[],
362    },
363    EntityTypeDef {
364        kind: EntityKind::Service,
365        type_name: "embedding_engine",
366        aliases: &[],
367    },
368    EntityTypeDef {
369        kind: EntityKind::Service,
370        type_name: "api",
371        aliases: &["endpoint"],
372    },
373    EntityTypeDef {
374        kind: EntityKind::Service,
375        type_name: "database",
376        aliases: &["db"],
377    },
378    EntityTypeDef {
379        kind: EntityKind::Service,
380        type_name: "search_engine",
381        aliases: &[],
382    },
383    EntityTypeDef {
384        kind: EntityKind::Service,
385        type_name: "mcp_server",
386        aliases: &["mcp"],
387    },
388    EntityTypeDef {
389        kind: EntityKind::Service,
390        type_name: "site",
391        aliases: &["origin"],
392    },
393    // Person  — no standard subtypes (roles are metadata, not subtypes).
394];
395
396/// Resolved output of [`EntityTypeRegistry::resolve`].
397#[derive(Clone, Debug, PartialEq, Eq)]
398pub struct ResolvedEntityType {
399    /// The canonical `EntityKind` for the resolved combination.
400    pub kind: EntityKind,
401    /// The canonical type name to store, or `None` when no `entity_type` was
402    /// supplied and none was inferred.
403    pub entity_type: Option<String>,
404}
405
406/// Appended to every unknown-type refusal so a caller learns that the list is
407/// closed for the store and where a domain-specific type can go instead.
408pub const UNKNOWN_ENTITY_TYPE_HINT: &str = "Entity types come from the loaded packs and cannot be declared per store yet; record a domain-specific type in properties or tags.";
409
410/// Error produced by [`EntityTypeRegistry::resolve`].
411///
412/// Dependency-light: `khive-types` cannot depend on `khive-runtime`, so
413/// callers map this to their own error type at the pack boundary.
414#[derive(Clone, Debug, PartialEq, Eq)]
415pub enum EntityTypeError {
416    /// The raw type name exists, but belongs to a different `EntityKind`.
417    WrongKind {
418        raw_type: String,
419        actual_kind: &'static str,
420        expected_kind: &'static str,
421        valid: String,
422    },
423    /// The raw type name is not registered for any kind.
424    UnknownType {
425        raw_type: String,
426        kind: &'static str,
427        valid: String,
428    },
429}
430
431impl fmt::Display for EntityTypeError {
432    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433        match self {
434            Self::WrongKind {
435                raw_type,
436                actual_kind,
437                expected_kind,
438                valid,
439            } => write!(
440                f,
441                "entity_type {raw_type:?} belongs to {actual_kind:?}, not {expected_kind:?}; \
442                 valid types for {expected_kind:?}: {valid}",
443            ),
444            Self::UnknownType {
445                raw_type,
446                kind,
447                valid,
448            } => write!(
449                f,
450                "unknown entity_type {raw_type:?} for {kind:?}; valid: {valid}. {UNKNOWN_ENTITY_TYPE_HINT}"
451            ),
452        }
453    }
454}
455
456#[cfg(feature = "std")]
457impl std::error::Error for EntityTypeError {}
458
459/// Registry for `(EntityKind, entity_type)` pair validation and alias normalisation.
460#[derive(Clone)]
461pub struct EntityTypeRegistry {
462    /// `alias_or_name (lowercase) → def index`.  Covers both canonical names
463    /// and all registered aliases.
464    lookup: BTreeMap<String, usize>,
465    defs: Vec<EntityTypeDef>,
466}
467
468impl EntityTypeRegistry {
469    /// Build a fresh registry from the supplied definitions.
470    ///
471    /// Every lookup key (kind-qualified and bare, canonical and alias) is
472    /// routed through `to_snake_case` before insertion — the same
473    /// normalisation `resolve` applies to incoming wire values (ADR-001:106).
474    /// Two differently-cased/separated spellings that normalise to the same
475    /// key therefore land on the same registry slot instead of silently
476    /// shadowing one another under distinct raw keys.
477    pub fn new(defs: impl IntoIterator<Item = EntityTypeDef>) -> Self {
478        let defs: Vec<EntityTypeDef> = defs.into_iter().collect();
479        let mut lookup: BTreeMap<String, usize> = BTreeMap::new();
480        for (idx, def) in defs.iter().enumerate() {
481            let canonical_type = to_snake_case(def.type_name);
482            let canonical_key = format!("{}:{}", def.kind.name(), canonical_type);
483            lookup.insert(canonical_key, idx);
484            // Bare name without kind prefix — only insert when unambiguous.
485            lookup.entry(canonical_type).or_insert(idx);
486            for alias in def.aliases {
487                let normalised_alias = to_snake_case(alias);
488                let kind_alias_key = format!("{}:{}", def.kind.name(), normalised_alias);
489                lookup.insert(kind_alias_key, idx);
490                lookup.entry(normalised_alias).or_insert(idx);
491            }
492        }
493        Self { lookup, defs }
494    }
495
496    /// Return the built-in registry with all static subtype definitions.
497    pub fn builtin() -> Self {
498        Self::new(BUILTIN_DEFS.iter().cloned())
499    }
500
501    /// Derive a registry that includes all built-in subtypes plus the
502    /// caller-supplied extras (used by packs that extend the vocabulary).
503    pub fn with_extra(extra: impl IntoIterator<Item = EntityTypeDef>) -> Self {
504        let defs: Vec<EntityTypeDef> = BUILTIN_DEFS.iter().cloned().chain(extra).collect();
505        Self::new(defs)
506    }
507
508    /// Definitions in this composed registry, including canonical names and aliases.
509    pub fn definitions(&self) -> &[EntityTypeDef] {
510        &self.defs
511    }
512
513    /// Boot-time collision check across the composed registry `with_extra`
514    /// builds: built-in defs plus every caller-supplied `(owner, def)` extra.
515    ///
516    /// `new`/`register` populate a single kind-qualified lookup keyspace
517    /// (`"{kind}:{canonical_name}"` and `"{kind}:{alias}"`) with a hard
518    /// `insert` — the later write silently wins. Two independently loaded
519    /// owners can therefore disagree on what a given key resolves to, and
520    /// the winner depends on registration order. ADR-001's registry-ownership
521    /// contract instead requires this to fail at boot: "same `(base_kind,
522    /// canonical_name)` from two different packs = boot error" and "an alias
523    /// collision = boot error." This walks the same keyspace `new`/`register`
524    /// populate and returns the first collision found, naming both
525    /// contributing owners, instead of silently picking a winner.
526    ///
527    /// `extras` is `(owner_label, def)` for pack-declared entries only — the
528    /// built-in table is checked automatically, attributed to the label
529    /// `"builtin"`.
530    ///
531    /// Every canonical and alias key is routed through the same
532    /// `to_snake_case` normalisation `new`/`register` apply before
533    /// insertion (ADR-001:104-107): two spellings that only differ in case
534    /// or separator style (e.g. `"Architecture Decision Record"` vs.
535    /// `"architecture-decision-record"`) collide here exactly as they would
536    /// collide in the composed registry's lookup keyspace.
537    pub fn check_extra_collisions<'a>(
538        extras: impl IntoIterator<Item = (&'a str, &'a EntityTypeDef)>,
539    ) -> Result<(), String> {
540        let mut all: Vec<(&'a str, &'a EntityTypeDef)> =
541            BUILTIN_DEFS.iter().map(|def| ("builtin", def)).collect();
542        all.extend(extras);
543
544        let mut seen: BTreeMap<String, (&'a str, String)> = BTreeMap::new();
545        for (owner, def) in all {
546            let canonical_type = to_snake_case(def.type_name);
547            let canonical_key = format!("{}:{}", def.kind.name(), canonical_type);
548            if let Some((first_owner, first_type)) = seen.get(&canonical_key) {
549                if *first_owner != owner {
550                    return Err(format!(
551                        "duplicate entity_type {canonical_key:?}: claimed by both \
552                         {first_owner:?} and {owner:?}"
553                    ));
554                }
555                if *first_type != canonical_type {
556                    return Err(format!(
557                        "entity_type alias {canonical_key:?}: claimed by both {first_owner:?} \
558                         (canonical {first_type:?}) and {owner:?} (canonical {canonical_type:?})"
559                    ));
560                }
561            } else {
562                seen.insert(canonical_key, (owner, canonical_type.clone()));
563            }
564
565            for alias in def.aliases {
566                let normalised_alias = to_snake_case(alias);
567                let alias_key = format!("{}:{}", def.kind.name(), normalised_alias);
568                if let Some((first_owner, first_type)) = seen.get(&alias_key) {
569                    if *first_owner != owner || *first_type != canonical_type {
570                        return Err(format!(
571                            "entity_type alias {alias_key:?}: claimed by both {first_owner:?} \
572                             (canonical {first_type:?}) and {owner:?} (canonical {canonical_type:?})",
573                        ));
574                    }
575                } else {
576                    seen.insert(alias_key, (owner, canonical_type.clone()));
577                }
578            }
579        }
580        Ok(())
581    }
582
583    /// Register additional subtypes into an existing registry clone.
584    ///
585    /// Mirrors [`Self::new`]'s normalisation: every key is routed through
586    /// `to_snake_case` before insertion.
587    pub fn register(&mut self, def: EntityTypeDef) {
588        let idx = self.defs.len();
589        let canonical_type = to_snake_case(def.type_name);
590        let canonical_key = format!("{}:{}", def.kind.name(), canonical_type);
591        self.lookup.insert(canonical_key, idx);
592        self.lookup.entry(canonical_type).or_insert(idx);
593        for alias in def.aliases {
594            let normalised_alias = to_snake_case(alias);
595            let kind_alias_key = format!("{}:{}", def.kind.name(), normalised_alias);
596            self.lookup.insert(kind_alias_key, idx);
597            self.lookup.entry(normalised_alias).or_insert(idx);
598        }
599        self.defs.push(def);
600    }
601
602    /// Validate and normalise a `(kind, entity_type)` wire pair.
603    pub fn resolve(
604        &self,
605        kind: EntityKind,
606        entity_type: Option<&str>,
607    ) -> Result<ResolvedEntityType, EntityTypeError> {
608        let Some(raw_type) = entity_type else {
609            return Ok(ResolvedEntityType {
610                kind,
611                entity_type: None,
612            });
613        };
614
615        let normalised = to_snake_case(raw_type.trim());
616
617        // Try kind-qualified lookup first (unambiguous).
618        let kind_key = format!("{}:{}", kind.name(), normalised);
619        if let Some(&idx) = self.lookup.get(&kind_key) {
620            let def = &self.defs[idx];
621            return Ok(ResolvedEntityType {
622                kind,
623                entity_type: Some(def.type_name.to_string()),
624            });
625        }
626
627        // Try bare lookup — only valid when the bare name belongs to this kind.
628        if let Some(&idx) = self.lookup.get(&normalised) {
629            let def = &self.defs[idx];
630            if def.kind == kind {
631                return Ok(ResolvedEntityType {
632                    kind,
633                    entity_type: Some(def.type_name.to_string()),
634                });
635            }
636            // The name exists but belongs to a different kind.
637            return Err(EntityTypeError::WrongKind {
638                raw_type: raw_type.to_string(),
639                actual_kind: def.kind.name(),
640                expected_kind: kind.name(),
641                valid: self.valid_types_for(kind),
642            });
643        }
644
645        // Not found at all.
646        Err(EntityTypeError::UnknownType {
647            raw_type: raw_type.to_string(),
648            kind: kind.name(),
649            valid: self.valid_types_for(kind),
650        })
651    }
652
653    /// Comma-separated list of canonical type names valid for `kind`.
654    pub fn valid_types_for(&self, kind: EntityKind) -> String {
655        let mut names: Vec<&str> = self
656            .defs
657            .iter()
658            .filter(|d| d.kind == kind)
659            .map(|d| d.type_name)
660            .collect();
661        names.sort_unstable();
662        if names.is_empty() {
663            "(none registered)".to_string()
664        } else {
665            names.join(" | ")
666        }
667    }
668}
669
670// ── Module-level lazy global ─────────────────────────────────────────────────
671
672#[cfg(feature = "std")]
673static GLOBAL_REGISTRY: std::sync::OnceLock<EntityTypeRegistry> = std::sync::OnceLock::new();
674
675#[cfg(feature = "std")]
676impl EntityTypeRegistry {
677    /// Return a reference to the module-level built-in registry.
678    pub fn global() -> &'static EntityTypeRegistry {
679        GLOBAL_REGISTRY.get_or_init(EntityTypeRegistry::builtin)
680    }
681}
682
683// ── Tests ────────────────────────────────────────────────────────────────────
684
685#[cfg(test)]
686#[path = "entity_type_tests.rs"]
687mod tests;