khive-types 0.5.0

Core type primitives: Id128, Timestamp, Namespace, and the 3 substrate data types (Note, Entity, Event).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
//! EntityTypeRegistry — validates and normalises `(EntityKind, entity_type)` pairs.
//!
//! Canonical, dependency-light home for the closed entity-subtype taxonomy
//! (#571): both KG create validation and schedule replay validation resolve
//! against this single registry instead of maintaining separate copies.

use alloc::collections::BTreeMap;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::fmt;

use crate::entity::EntityKind;

/// Normalise a raw `entity_type` string to canonical snake_case.
///
/// Pipeline: trim → lowercase → runs of separators (space, hyphen, underscore)
/// collapsed to a single `_` → leading/trailing `_` stripped.
///
/// This implements the ADR-001:106 write-time normalisation step that precedes
/// alias resolution.
fn to_snake_case(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut prev_sep = true; // treat start as separator so leading _ are stripped
    for ch in s.chars() {
        if ch == ' ' || ch == '-' || ch == '_' {
            if !prev_sep && !out.is_empty() {
                out.push('_');
                prev_sep = true;
            }
        } else {
            out.push(ch.to_ascii_lowercase());
            prev_sep = false;
        }
    }
    if out.ends_with('_') {
        out.pop();
    }
    out
}

/// One entry in the registry: a canonical subtype name for a specific kind,
/// together with any accepted aliases.
#[derive(Clone, Debug)]
pub struct EntityTypeDef {
    /// The entity kind this subtype belongs to.
    pub kind: EntityKind,
    /// Canonical name that is written to the DB.
    pub type_name: &'static str,
    /// Alternative spellings that are accepted at the wire level but
    /// normalised to `type_name` before storage.
    pub aliases: &'static [&'static str],
}

/// Static table of built-in subtypes (non-exhaustive; packs may extend).
static BUILTIN_DEFS: &[EntityTypeDef] = &[
    // ── Document ────────────────────────────────────────────────────────────
    EntityTypeDef {
        kind: EntityKind::Document,
        type_name: "paper",
        aliases: &["preprint", "article"],
    },
    EntityTypeDef {
        kind: EntityKind::Document,
        type_name: "report",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Document,
        type_name: "blog_post",
        aliases: &["blog"],
    },
    EntityTypeDef {
        kind: EntityKind::Document,
        type_name: "book",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Document,
        type_name: "specification",
        aliases: &["spec"],
    },
    EntityTypeDef {
        kind: EntityKind::Document,
        type_name: "documentation",
        aliases: &["docs"],
    },
    EntityTypeDef {
        kind: EntityKind::Document,
        type_name: "thesis",
        aliases: &[],
    },
    // ── Concept ─────────────────────────────────────────────────────────────
    EntityTypeDef {
        kind: EntityKind::Concept,
        type_name: "algorithm",
        aliases: &["algo"],
    },
    // ── Formal math ─────────────────────────────────────────────────────────
    EntityTypeDef {
        kind: EntityKind::Concept,
        type_name: "theorem",
        aliases: &["lemma", "proposition", "corollary"],
    },
    EntityTypeDef {
        kind: EntityKind::Concept,
        type_name: "definition",
        aliases: &["def"],
    },
    EntityTypeDef {
        kind: EntityKind::Concept,
        type_name: "structure",
        aliases: &["inductive", "struct", "class"],
    },
    EntityTypeDef {
        kind: EntityKind::Concept,
        type_name: "instance",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Concept,
        type_name: "axiom",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Concept,
        type_name: "goal",
        aliases: &["proof_goal"],
    },
    EntityTypeDef {
        kind: EntityKind::Concept,
        type_name: "technique",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Concept,
        type_name: "architecture",
        aliases: &["arch"],
    },
    EntityTypeDef {
        kind: EntityKind::Concept,
        // "model" is the alias; canonical name is "model_family"
        // to distinguish from a Dataset or Artifact trained model instance.
        type_name: "model_family",
        aliases: &["model"],
    },
    EntityTypeDef {
        kind: EntityKind::Concept,
        type_name: "theory",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Concept,
        type_name: "research_gap",
        aliases: &["gap"],
    },
    EntityTypeDef {
        kind: EntityKind::Concept,
        type_name: "design_pattern",
        aliases: &["pattern"],
    },
    EntityTypeDef {
        kind: EntityKind::Concept,
        type_name: "mathematical_operation",
        aliases: &["math_op"],
    },
    EntityTypeDef {
        kind: EntityKind::Concept,
        type_name: "metric",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Concept,
        type_name: "objective",
        aliases: &["loss"],
    },
    // ── Code (ADR-085) ──────────────────────────────────────────────────────
    // "struct" and "class" are not registered as aliases here: formal-math
    // "structure" already owns them (see above), and ADR-085 requires
    // ingesters to write the canonical code tokens instead.
    EntityTypeDef {
        kind: EntityKind::Concept,
        type_name: "module",
        aliases: &["mod", "namespace"],
    },
    EntityTypeDef {
        kind: EntityKind::Concept,
        type_name: "function",
        aliases: &["fn", "func", "method"],
    },
    EntityTypeDef {
        kind: EntityKind::Concept,
        type_name: "datatype",
        aliases: &["enum", "record", "type_alias"],
    },
    EntityTypeDef {
        kind: EntityKind::Concept,
        type_name: "interface",
        aliases: &["trait", "protocol"],
    },
    // ── Dataset ──────────────────────────────────────────────────────────────
    // benchmark belongs to Dataset, not Concept (it evaluates models, it is not itself a concept).
    EntityTypeDef {
        kind: EntityKind::Dataset,
        type_name: "benchmark",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Dataset,
        type_name: "corpus",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Dataset,
        type_name: "training_set",
        aliases: &["train_set"],
    },
    EntityTypeDef {
        kind: EntityKind::Dataset,
        type_name: "evaluation_set",
        aliases: &["eval_set"],
    },
    EntityTypeDef {
        kind: EntityKind::Dataset,
        type_name: "test_set",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Dataset,
        type_name: "synthetic_dataset",
        aliases: &["synthetic"],
    },
    // ── Project ─────────────────────────────────────────────────────────────
    // Project subtypes: library, framework, tool, application, repository.
    // "service" and "svc" are omitted — EntityKind::Service handles running
    // instances; a service codebase repo is Project + application or tool.
    EntityTypeDef {
        kind: EntityKind::Project,
        type_name: "library",
        aliases: &["lib"],
    },
    EntityTypeDef {
        kind: EntityKind::Project,
        type_name: "framework",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Project,
        type_name: "tool",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Project,
        type_name: "application",
        aliases: &["app"],
    },
    EntityTypeDef {
        kind: EntityKind::Project,
        type_name: "repository",
        aliases: &["repo"],
    },
    // ── Org ──────────────────────────────────────────────────────────────────
    EntityTypeDef {
        kind: EntityKind::Org,
        type_name: "academic_institution",
        aliases: &["university", "uni"],
    },
    EntityTypeDef {
        kind: EntityKind::Org,
        type_name: "company",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Org,
        type_name: "research_lab",
        aliases: &["lab"],
    },
    EntityTypeDef {
        kind: EntityKind::Org,
        type_name: "nonprofit",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Org,
        type_name: "government_agency",
        aliases: &["gov_agency"],
    },
    EntityTypeDef {
        kind: EntityKind::Org,
        type_name: "consortium",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Org,
        type_name: "standards_body",
        aliases: &[],
    },
    // ── Artifact ─────────────────────────────────────────────────────────────
    EntityTypeDef {
        kind: EntityKind::Artifact,
        type_name: "checkpoint",
        aliases: &["ckpt"],
    },
    EntityTypeDef {
        kind: EntityKind::Artifact,
        type_name: "snapshot",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Artifact,
        type_name: "export",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Artifact,
        type_name: "embedding_index",
        aliases: &["embed_index"],
    },
    EntityTypeDef {
        kind: EntityKind::Artifact,
        type_name: "state_bundle",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Artifact,
        type_name: "profile",
        aliases: &[],
    },
    // ── Service ──────────────────────────────────────────────────────────────
    // Service subtypes: inference_engine, retrieval_engine,
    // embedding_engine, api, database, search_engine, mcp_server.
    EntityTypeDef {
        kind: EntityKind::Service,
        type_name: "inference_engine",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Service,
        type_name: "retrieval_engine",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Service,
        type_name: "embedding_engine",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Service,
        type_name: "api",
        aliases: &["endpoint"],
    },
    EntityTypeDef {
        kind: EntityKind::Service,
        type_name: "database",
        aliases: &["db"],
    },
    EntityTypeDef {
        kind: EntityKind::Service,
        type_name: "search_engine",
        aliases: &[],
    },
    EntityTypeDef {
        kind: EntityKind::Service,
        type_name: "mcp_server",
        aliases: &["mcp"],
    },
    // Person  — no standard subtypes (roles are metadata, not subtypes).
];

/// Resolved output of [`EntityTypeRegistry::resolve`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResolvedEntityType {
    /// The canonical `EntityKind` for the resolved combination.
    pub kind: EntityKind,
    /// The canonical type name to store, or `None` when no `entity_type` was
    /// supplied and none was inferred.
    pub entity_type: Option<String>,
}

/// Error produced by [`EntityTypeRegistry::resolve`].
///
/// Dependency-light: `khive-types` cannot depend on `khive-runtime`, so
/// callers map this to their own error type at the pack boundary.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EntityTypeError {
    /// The raw type name exists, but belongs to a different `EntityKind`.
    WrongKind {
        raw_type: String,
        actual_kind: &'static str,
        expected_kind: &'static str,
        valid: String,
    },
    /// The raw type name is not registered for any kind.
    UnknownType {
        raw_type: String,
        kind: &'static str,
        valid: String,
    },
}

impl fmt::Display for EntityTypeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::WrongKind {
                raw_type,
                actual_kind,
                expected_kind,
                valid,
            } => write!(
                f,
                "entity_type {raw_type:?} belongs to {actual_kind:?}, not {expected_kind:?}; \
                 valid types for {expected_kind:?}: {valid}",
            ),
            Self::UnknownType {
                raw_type,
                kind,
                valid,
            } => write!(
                f,
                "unknown entity_type {raw_type:?} for {kind:?}; valid: {valid}"
            ),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for EntityTypeError {}

/// Registry for `(EntityKind, entity_type)` pair validation and alias normalisation.
#[derive(Clone)]
pub struct EntityTypeRegistry {
    /// `alias_or_name (lowercase) → def index`.  Covers both canonical names
    /// and all registered aliases.
    lookup: BTreeMap<String, usize>,
    defs: Vec<EntityTypeDef>,
}

impl EntityTypeRegistry {
    /// Build a fresh registry from the supplied definitions.
    ///
    /// Every lookup key (kind-qualified and bare, canonical and alias) is
    /// routed through `to_snake_case` before insertion — the same
    /// normalisation `resolve` applies to incoming wire values (ADR-001:106).
    /// Two differently-cased/separated spellings that normalise to the same
    /// key therefore land on the same registry slot instead of silently
    /// shadowing one another under distinct raw keys.
    pub fn new(defs: impl IntoIterator<Item = EntityTypeDef>) -> Self {
        let defs: Vec<EntityTypeDef> = defs.into_iter().collect();
        let mut lookup: BTreeMap<String, usize> = BTreeMap::new();
        for (idx, def) in defs.iter().enumerate() {
            let canonical_type = to_snake_case(def.type_name);
            let canonical_key = format!("{}:{}", def.kind.name(), canonical_type);
            lookup.insert(canonical_key, idx);
            // Bare name without kind prefix — only insert when unambiguous.
            lookup.entry(canonical_type).or_insert(idx);
            for alias in def.aliases {
                let normalised_alias = to_snake_case(alias);
                let kind_alias_key = format!("{}:{}", def.kind.name(), normalised_alias);
                lookup.insert(kind_alias_key, idx);
                lookup.entry(normalised_alias).or_insert(idx);
            }
        }
        Self { lookup, defs }
    }

    /// Return the built-in registry with all static subtype definitions.
    pub fn builtin() -> Self {
        Self::new(BUILTIN_DEFS.iter().cloned())
    }

    /// Derive a registry that includes all built-in subtypes plus the
    /// caller-supplied extras (used by packs that extend the vocabulary).
    pub fn with_extra(extra: impl IntoIterator<Item = EntityTypeDef>) -> Self {
        let defs: Vec<EntityTypeDef> = BUILTIN_DEFS.iter().cloned().chain(extra).collect();
        Self::new(defs)
    }

    /// Boot-time collision check across the composed registry `with_extra`
    /// builds: built-in defs plus every caller-supplied `(owner, def)` extra.
    ///
    /// `new`/`register` populate a single kind-qualified lookup keyspace
    /// (`"{kind}:{canonical_name}"` and `"{kind}:{alias}"`) with a hard
    /// `insert` — the later write silently wins. Two independently loaded
    /// owners can therefore disagree on what a given key resolves to, and
    /// the winner depends on registration order. ADR-001's registry-ownership
    /// contract instead requires this to fail at boot: "same `(base_kind,
    /// canonical_name)` from two different packs = boot error" and "an alias
    /// collision = boot error." This walks the same keyspace `new`/`register`
    /// populate and returns the first collision found, naming both
    /// contributing owners, instead of silently picking a winner.
    ///
    /// `extras` is `(owner_label, def)` for pack-declared entries only — the
    /// built-in table is checked automatically, attributed to the label
    /// `"builtin"`.
    ///
    /// Every canonical and alias key is routed through the same
    /// `to_snake_case` normalisation `new`/`register` apply before
    /// insertion (ADR-001:104-107): two spellings that only differ in case
    /// or separator style (e.g. `"Architecture Decision Record"` vs.
    /// `"architecture-decision-record"`) collide here exactly as they would
    /// collide in the composed registry's lookup keyspace.
    pub fn check_extra_collisions<'a>(
        extras: impl IntoIterator<Item = (&'a str, &'a EntityTypeDef)>,
    ) -> Result<(), String> {
        let mut all: Vec<(&'a str, &'a EntityTypeDef)> =
            BUILTIN_DEFS.iter().map(|def| ("builtin", def)).collect();
        all.extend(extras);

        let mut seen: BTreeMap<String, (&'a str, String)> = BTreeMap::new();
        for (owner, def) in all {
            let canonical_type = to_snake_case(def.type_name);
            let canonical_key = format!("{}:{}", def.kind.name(), canonical_type);
            if let Some((first_owner, _)) = seen.get(&canonical_key) {
                if *first_owner != owner {
                    return Err(format!(
                        "duplicate entity_type {canonical_key:?}: claimed by both \
                         {first_owner:?} and {owner:?}"
                    ));
                }
            } else {
                seen.insert(canonical_key, (owner, canonical_type.clone()));
            }

            for alias in def.aliases {
                let normalised_alias = to_snake_case(alias);
                let alias_key = format!("{}:{}", def.kind.name(), normalised_alias);
                if let Some((first_owner, first_type)) = seen.get(&alias_key) {
                    if *first_owner != owner || *first_type != canonical_type {
                        return Err(format!(
                            "entity_type alias {alias_key:?}: claimed by both {first_owner:?} \
                             (canonical {first_type:?}) and {owner:?} (canonical {canonical_type:?})",
                        ));
                    }
                } else {
                    seen.insert(alias_key, (owner, canonical_type.clone()));
                }
            }
        }
        Ok(())
    }

    /// Register additional subtypes into an existing registry clone.
    ///
    /// Mirrors [`Self::new`]'s normalisation: every key is routed through
    /// `to_snake_case` before insertion.
    pub fn register(&mut self, def: EntityTypeDef) {
        let idx = self.defs.len();
        let canonical_type = to_snake_case(def.type_name);
        let canonical_key = format!("{}:{}", def.kind.name(), canonical_type);
        self.lookup.insert(canonical_key, idx);
        self.lookup.entry(canonical_type).or_insert(idx);
        for alias in def.aliases {
            let normalised_alias = to_snake_case(alias);
            let kind_alias_key = format!("{}:{}", def.kind.name(), normalised_alias);
            self.lookup.insert(kind_alias_key, idx);
            self.lookup.entry(normalised_alias).or_insert(idx);
        }
        self.defs.push(def);
    }

    /// Validate and normalise a `(kind, entity_type)` wire pair.
    pub fn resolve(
        &self,
        kind: EntityKind,
        entity_type: Option<&str>,
    ) -> Result<ResolvedEntityType, EntityTypeError> {
        let Some(raw_type) = entity_type else {
            return Ok(ResolvedEntityType {
                kind,
                entity_type: None,
            });
        };

        let normalised = to_snake_case(raw_type.trim());

        // Try kind-qualified lookup first (unambiguous).
        let kind_key = format!("{}:{}", kind.name(), normalised);
        if let Some(&idx) = self.lookup.get(&kind_key) {
            let def = &self.defs[idx];
            return Ok(ResolvedEntityType {
                kind,
                entity_type: Some(def.type_name.to_string()),
            });
        }

        // Try bare lookup — only valid when the bare name belongs to this kind.
        if let Some(&idx) = self.lookup.get(&normalised) {
            let def = &self.defs[idx];
            if def.kind == kind {
                return Ok(ResolvedEntityType {
                    kind,
                    entity_type: Some(def.type_name.to_string()),
                });
            }
            // The name exists but belongs to a different kind.
            return Err(EntityTypeError::WrongKind {
                raw_type: raw_type.to_string(),
                actual_kind: def.kind.name(),
                expected_kind: kind.name(),
                valid: self.valid_types_for(kind),
            });
        }

        // Not found at all.
        Err(EntityTypeError::UnknownType {
            raw_type: raw_type.to_string(),
            kind: kind.name(),
            valid: self.valid_types_for(kind),
        })
    }

    /// Comma-separated list of canonical type names valid for `kind`.
    pub fn valid_types_for(&self, kind: EntityKind) -> String {
        let mut names: Vec<&str> = self
            .defs
            .iter()
            .filter(|d| d.kind == kind)
            .map(|d| d.type_name)
            .collect();
        names.sort_unstable();
        if names.is_empty() {
            "(none registered)".to_string()
        } else {
            names.join(" | ")
        }
    }
}

// ── Module-level lazy global ─────────────────────────────────────────────────

#[cfg(feature = "std")]
static GLOBAL_REGISTRY: std::sync::OnceLock<EntityTypeRegistry> = std::sync::OnceLock::new();

#[cfg(feature = "std")]
impl EntityTypeRegistry {
    /// Return a reference to the module-level built-in registry.
    pub fn global() -> &'static EntityTypeRegistry {
        GLOBAL_REGISTRY.get_or_init(EntityTypeRegistry::builtin)
    }
}

// ── Tests ────────────────────────────────────────────────────────────────────

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

    fn reg() -> EntityTypeRegistry {
        EntityTypeRegistry::builtin()
    }

    // ── Basic happy-path resolution ──────────────────────────────────────────

    #[test]
    fn resolve_paper_infers_document() {
        let r = reg();
        let res = r
            .resolve(EntityKind::Document, Some("paper"))
            .expect("paper is a valid Document subtype");
        assert_eq!(res.kind, EntityKind::Document);
        assert_eq!(res.entity_type.as_deref(), Some("paper"));
    }

    #[test]
    fn resolve_none_entity_type_always_ok() {
        let r = reg();
        for kind in EntityKind::ALL {
            let res = r.resolve(kind, None).expect("None entity_type always ok");
            assert_eq!(res.entity_type, None);
        }
    }

    #[test]
    fn resolve_algo_alias_to_algorithm() {
        let r = reg();
        let res = r
            .resolve(EntityKind::Concept, Some("algo"))
            .expect("algo is a valid alias for algorithm");
        assert_eq!(res.kind, EntityKind::Concept);
        assert_eq!(res.entity_type.as_deref(), Some("algorithm"));
    }

    #[test]
    fn resolve_spec_alias_to_specification() {
        let r = reg();
        let res = r
            .resolve(EntityKind::Document, Some("spec"))
            .expect("spec is alias for specification");
        assert_eq!(res.entity_type.as_deref(), Some("specification"));
    }

    // ── Rejection tests ──────────────────────────────────────────────────────

    #[test]
    fn reject_brain_profile_for_concept() {
        let r = reg();
        let err = r
            .resolve(EntityKind::Concept, Some("brain_profile"))
            .expect_err("brain_profile is not a Concept subtype");
        let msg = format!("{err}");
        assert!(
            msg.contains("brain_profile"),
            "error must mention the rejected type; got: {msg}"
        );
        assert!(
            msg.contains("concept"),
            "error must mention the target kind; got: {msg}"
        );
    }

    #[test]
    fn reject_unknown_subtype_with_valid_list() {
        let r = reg();
        let err = r
            .resolve(EntityKind::Document, Some("mystery_type"))
            .expect_err("mystery_type must be rejected");
        let msg = format!("{err}");
        assert!(
            msg.contains("mystery_type"),
            "error must echo the rejected value; got: {msg}"
        );
        // Valid subtypes for Document must appear.
        assert!(
            msg.contains("paper"),
            "error must list valid Document subtypes; got: {msg}"
        );
    }

    #[test]
    fn reject_wrong_kind_subtype_mentions_correct_kind() {
        // "paper" belongs to Document; passing it for Concept must fail.
        let r = reg();
        let err = r
            .resolve(EntityKind::Concept, Some("paper"))
            .expect_err("paper is a Document subtype, not Concept");
        let msg = format!("{err}");
        assert!(
            msg.contains("document") || msg.contains("Document"),
            "error must name the correct kind; got: {msg}"
        );
    }

    // ── Extensibility ────────────────────────────────────────────────────────

    #[test]
    fn register_brain_profile_for_concept() {
        let mut r = EntityTypeRegistry::builtin();
        r.register(EntityTypeDef {
            kind: EntityKind::Concept,
            type_name: "brain_profile",
            aliases: &[],
        });
        let res = r
            .resolve(EntityKind::Concept, Some("brain_profile"))
            .expect("brain_profile registered for Concept");
        assert_eq!(res.entity_type.as_deref(), Some("brain_profile"));
    }

    #[test]
    fn with_extra_adds_subtypes() {
        // Use a pack-specific subtype that is NOT in BUILTIN_DEFS.
        let r = EntityTypeRegistry::with_extra([EntityTypeDef {
            kind: EntityKind::Service,
            type_name: "grpc_service",
            aliases: &["grpc"],
        }]);
        let res = r
            .resolve(EntityKind::Service, Some("grpc"))
            .expect("grpc alias for grpc_service");
        assert_eq!(res.entity_type.as_deref(), Some("grpc_service"));
    }

    #[test]
    fn service_api_is_builtin() {
        let r = reg();
        let res = r
            .resolve(EntityKind::Service, Some("api"))
            .expect("api is a built-in Service subtype");
        assert_eq!(res.entity_type.as_deref(), Some("api"));
        let res2 = r
            .resolve(EntityKind::Service, Some("endpoint"))
            .expect("endpoint is an alias for api");
        assert_eq!(res2.entity_type.as_deref(), Some("api"));
    }

    #[test]
    fn service_mcp_server_is_builtin() {
        let r = reg();
        let res = r
            .resolve(EntityKind::Service, Some("mcp_server"))
            .expect("mcp_server is a built-in Service subtype");
        assert_eq!(res.entity_type.as_deref(), Some("mcp_server"));
        let res2 = r
            .resolve(EntityKind::Service, Some("mcp"))
            .expect("mcp is an alias for mcp_server");
        assert_eq!(res2.entity_type.as_deref(), Some("mcp_server"));
    }

    #[test]
    fn project_has_no_service_subtype() {
        let r = reg();
        r.resolve(EntityKind::Project, Some("service"))
            .expect_err("service must not be a Project subtype");
        r.resolve(EntityKind::Project, Some("svc"))
            .expect_err("svc must not be a Project subtype");
    }

    #[test]
    fn benchmark_is_dataset_not_concept() {
        let r = reg();
        let res = r
            .resolve(EntityKind::Dataset, Some("benchmark"))
            .expect("benchmark is a valid Dataset subtype");
        assert_eq!(res.entity_type.as_deref(), Some("benchmark"));
        r.resolve(EntityKind::Concept, Some("benchmark"))
            .expect_err("benchmark must not be a Concept subtype");
    }

    #[test]
    fn model_alias_resolves_to_model_family() {
        let r = reg();
        let res = r
            .resolve(EntityKind::Concept, Some("model"))
            .expect("model is an alias for model_family");
        assert_eq!(res.entity_type.as_deref(), Some("model_family"));
        let res2 = r
            .resolve(EntityKind::Concept, Some("model_family"))
            .expect("model_family is the canonical name");
        assert_eq!(res2.entity_type.as_deref(), Some("model_family"));
    }

    // ── Case insensitivity ───────────────────────────────────────────────────

    #[test]
    fn resolve_is_case_insensitive() {
        let r = reg();
        let res = r
            .resolve(EntityKind::Concept, Some("Algorithm"))
            .expect("Algorithm (mixed case) must resolve");
        assert_eq!(res.entity_type.as_deref(), Some("algorithm"));
    }

    // ── valid_types_for ──────────────────────────────────────────────────────

    #[test]
    fn valid_types_for_person_is_none_registered() {
        let r = reg();
        let s = r.valid_types_for(EntityKind::Person);
        assert_eq!(
            s, "(none registered)",
            "Person has no built-in subtypes; got: {s}"
        );
    }

    #[test]
    fn valid_types_for_concept_includes_algorithm() {
        let r = reg();
        let s = r.valid_types_for(EntityKind::Concept);
        assert!(
            s.contains("algorithm"),
            "Concept valid types must include algorithm; got: {s}"
        );
    }

    #[test]
    fn resolve_inductive_alias_to_structure() {
        let r = reg();
        let res = r
            .resolve(EntityKind::Concept, Some("inductive"))
            .expect("inductive is a valid alias for structure");
        assert_eq!(res.kind, EntityKind::Concept);
        assert_eq!(res.entity_type.as_deref(), Some("structure"));
    }

    #[test]
    fn resolve_goal_subtype() {
        let r = reg();
        let res = r
            .resolve(EntityKind::Concept, Some("goal"))
            .expect("goal is a valid Concept subtype");
        assert_eq!(res.kind, EntityKind::Concept);
        assert_eq!(res.entity_type.as_deref(), Some("goal"));
    }

    // ── Global registry ──────────────────────────────────────────────────────

    #[cfg(feature = "std")]
    #[test]
    fn global_registry_is_accessible() {
        let r = EntityTypeRegistry::global();
        let res = r
            .resolve(EntityKind::Document, Some("paper"))
            .expect("global registry must resolve paper");
        assert_eq!(res.entity_type.as_deref(), Some("paper"));
    }

    // ── snake_case normalisation (ADR-001:106) ───────────────────────────────

    #[test]
    fn to_snake_case_converts_hyphen_to_underscore() {
        assert_eq!(to_snake_case("proof-goal"), "proof_goal");
    }

    #[test]
    fn to_snake_case_converts_space_to_underscore() {
        assert_eq!(to_snake_case("Proof Goal"), "proof_goal");
    }

    #[test]
    fn to_snake_case_collapses_mixed_separators() {
        assert_eq!(to_snake_case("proof - goal"), "proof_goal");
        assert_eq!(to_snake_case("proof__goal"), "proof_goal");
    }

    #[test]
    fn to_snake_case_strips_leading_trailing_separators() {
        assert_eq!(to_snake_case("-theorem-"), "theorem");
        assert_eq!(to_snake_case(" theorem "), "theorem");
    }

    #[test]
    fn resolve_proof_goal_hyphen_normalises_to_goal() {
        let r = reg();
        let res = r
            .resolve(EntityKind::Concept, Some("proof-goal"))
            .expect("proof-goal must resolve via snake_case normalisation + alias");
        assert_eq!(res.entity_type.as_deref(), Some("goal"));
    }

    #[test]
    fn resolve_proof_goal_space_normalises_to_goal() {
        let r = reg();
        let res = r
            .resolve(EntityKind::Concept, Some("Proof Goal"))
            .expect("Proof Goal must resolve via snake_case normalisation + alias");
        assert_eq!(res.entity_type.as_deref(), Some("goal"));
    }

    #[test]
    fn resolve_blog_hyphen_normalises_to_blog_post_non_formal() {
        let r = reg();
        let res = r
            .resolve(EntityKind::Document, Some("blog-post"))
            .expect("blog-post must normalise to blog_post");
        assert_eq!(res.entity_type.as_deref(), Some("blog_post"));
    }

    // ── ADR-085 code subtypes ────────────────────────────────────────────────

    #[test]
    fn entity_type_registry_accepts_code_tokens_and_aliases() {
        let r = reg();
        for (raw, canonical) in [
            ("module", "module"),
            ("mod", "module"),
            ("namespace", "module"),
            ("function", "function"),
            ("fn", "function"),
            ("func", "function"),
            ("method", "function"),
            ("datatype", "datatype"),
            ("enum", "datatype"),
            ("record", "datatype"),
            ("type_alias", "datatype"),
            ("interface", "interface"),
            ("trait", "interface"),
            ("protocol", "interface"),
        ] {
            let res = r
                .resolve(EntityKind::Concept, Some(raw))
                .unwrap_or_else(|e| panic!("{raw:?} must resolve for Concept: {e}"));
            assert_eq!(
                res.entity_type.as_deref(),
                Some(canonical),
                "{raw:?} must resolve to {canonical:?}"
            );
        }
    }

    #[test]
    fn entity_type_registry_does_not_claim_struct_or_class_for_code() {
        let r = reg();
        let struct_res = r
            .resolve(EntityKind::Concept, Some("struct"))
            .expect("struct remains a valid Concept subtype (owned by formal structure)");
        assert_eq!(
            struct_res.entity_type.as_deref(),
            Some("structure"),
            "struct must still resolve to formal-math structure, not datatype"
        );
        let class_res = r
            .resolve(EntityKind::Concept, Some("class"))
            .expect("class remains a valid Concept subtype (owned by formal structure)");
        assert_eq!(
            class_res.entity_type.as_deref(),
            Some("structure"),
            "class must still resolve to formal-math structure, not datatype"
        );
    }

    // ── check_extra_collisions: ADR-001 normalisation (PR #925) ──
    //
    // `check_extra_collisions` must reject collisions that only become
    // visible after ADR-001:104-107's write-time `to_snake_case`
    // normalisation — i.e. two raw spellings that differ in case or
    // separator style but land on the same kind-qualified key once
    // normalised. Before the r2 fix these three cases silently passed
    // (`Ok(())`) because the check compared raw, unnormalised strings.

    #[test]
    fn check_extra_collisions_detects_normalized_alias_vs_alias() {
        let def_a = EntityTypeDef {
            kind: EntityKind::Service,
            type_name: "widget_service",
            aliases: &["Widget-Alias"],
        };
        let def_b = EntityTypeDef {
            kind: EntityKind::Service,
            type_name: "gadget_service",
            aliases: &["widget_alias"],
        };
        let err =
            EntityTypeRegistry::check_extra_collisions([("pack_a", &def_a), ("pack_b", &def_b)])
                .expect_err(
                    "aliases that only differ in case/hyphenation but normalise to the same \
             kind-qualified key must collide",
                );
        assert!(err.contains("pack_a"), "error must name pack_a: {err}");
        assert!(err.contains("pack_b"), "error must name pack_b: {err}");
    }

    #[test]
    fn check_extra_collisions_detects_normalized_alias_vs_canonical() {
        let def_a = EntityTypeDef {
            kind: EntityKind::Service,
            type_name: "primary_service",
            aliases: &[],
        };
        let def_b = EntityTypeDef {
            kind: EntityKind::Service,
            type_name: "secondary_service",
            aliases: &["Primary-Service"],
        };
        let err =
            EntityTypeRegistry::check_extra_collisions([("pack_a", &def_a), ("pack_b", &def_b)])
                .expect_err(
                    "an alias that normalises onto another owner's canonical key must collide, \
             even when the raw spellings differ",
                );
        assert!(err.contains("pack_a"), "error must name pack_a: {err}");
        assert!(err.contains("pack_b"), "error must name pack_b: {err}");
    }

    #[test]
    fn check_extra_collisions_detects_normalized_builtin_vs_pack_collision() {
        // BUILTIN_DEFS declares Document "paper". A pack declaring a
        // differently-cased spelling that normalises onto the same
        // kind-qualified key must still collide with the built-in owner.
        let def = EntityTypeDef {
            kind: EntityKind::Document,
            type_name: "Paper",
            aliases: &[],
        };
        let err = EntityTypeRegistry::check_extra_collisions([("pack_a", &def)]).expect_err(
            "a pack canonical name that normalises onto a builtin canonical key must collide",
        );
        assert!(err.contains("builtin"), "error must name builtin: {err}");
        assert!(err.contains("pack_a"), "error must name pack_a: {err}");
    }
}