canwu-core 0.13.0

Stable IDs, deterministic random numbers, and schema primitives for Canwu
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
//! Stable identifiers, deterministic utilities, and lightweight schema metadata.

use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::fmt::{Display, Formatter};
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;

macro_rules! define_id {
    ($name:ident) => {
        #[derive(
            Clone,
            Copy,
            Debug,
            Default,
            Deserialize,
            Eq,
            Hash,
            Ord,
            PartialEq,
            PartialOrd,
            Serialize,
        )]
        #[serde(transparent)]
        #[doc = concat!("Stable numeric identifier for [`", stringify!($name), "`].")]
        pub struct $name(pub u64);

        impl $name {
            /// Creates an identifier from its wire value.
            #[must_use]
            pub const fn new(value: u64) -> Self {
                Self(value)
            }

            /// Returns the identifier's wire value.
            #[must_use]
            pub const fn get(self) -> u64 {
                self.0
            }
        }

        impl Display for $name {
            fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
                Display::fmt(&self.0, formatter)
            }
        }
    };
}

define_id!(ArmyId);
define_id!(BoundaryId);
define_id!(CommandAttemptId);
define_id!(CommandId);
define_id!(CommandRequestId);
define_id!(DecisionRequestId);
define_id!(DecisionTicketId);
define_id!(DecisionTraceId);
define_id!(EventId);
define_id!(GovernmentId);
define_id!(IngressId);
define_id!(HolderKnowledgeRecordId);
define_id!(LetterId);
define_id!(OrganizationId);
define_id!(PersonId);
define_id!(RandomDrawId);
define_id!(KnowledgeRecordId);
define_id!(ResourceId);
define_id!(RouteId);
define_id!(TerritoryId);

/// Generic simulation granularity used by host applications to map aggregate,
/// group, and individual actors onto the same authoritative engine.
///
/// The engine deliberately does not call these levels "population", "special
/// group", or "character". Those are content terms owned by a reference
/// integration such as Celestial Mandate. A host may map its population model
/// to [`Self::Aggregate`], its special groups to [`Self::Group`], and its
/// characters to [`Self::Actor`] without changing the kernel's identity wire
/// format.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SimulationGranularity {
    Aggregate,
    Group,
    Actor,
}

impl SimulationGranularity {
    /// Returns the stable public label used in manifests and diagnostics.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Aggregate => "aggregate",
            Self::Group => "group",
            Self::Actor => "actor",
        }
    }
}

/// Stable application-defined record kind. Namespaces and names are validated
/// by the simulation package registry before authoritative use.
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct DomainRecordKind {
    pub namespace: String,
    pub name: String,
}

impl DomainRecordKind {
    #[must_use]
    pub fn new(namespace: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            namespace: namespace.into(),
            name: name.into(),
        }
    }

    #[must_use]
    pub fn for_type<T: DomainRecordType>() -> Self {
        Self::new(T::NAMESPACE, T::NAME)
    }

    #[must_use]
    pub fn matches_type<T: DomainRecordType>(&self) -> bool {
        self.namespace == T::NAMESPACE && self.name == T::NAME
    }
}

impl Display for DomainRecordKind {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "{}.{}", self.namespace, self.name)
    }
}

/// Stable string identity for an application-defined entity or record.
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct DomainRecordRef {
    pub kind: DomainRecordKind,
    pub id: String,
}

/// Persisted identity of the operation that established one domain-record
/// version. Version zero is reserved and rejected by runtime validation.
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum DomainRecordVersionSource {
    InitialScenario,
    BoundaryChange {
        boundary: BoundaryId,
        change_index: u64,
    },
}

/// Exact historical identity for an application-defined record version.
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct DomainRecordVersionRef {
    pub record: DomainRecordRef,
    pub version: u64,
    pub established_by: DomainRecordVersionSource,
}

/// Shared persisted-evidence identity used by knowledge, decisions, random
/// operations, replay, and compact archive receipts.
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum EvidenceRef {
    Command(CommandId),
    CommandAttempt(CommandAttemptId),
    Event(EventId),
    Ingress(IngressId),
    Boundary(BoundaryId),
    RandomDraw(RandomDrawId),
    DomainRecordVersion(DomainRecordVersionRef),
}

/// Stable namespace and kind for a holder-relative knowledge record.
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct KnowledgeRecordKind {
    pub namespace: String,
    pub name: String,
}

impl KnowledgeRecordKind {
    #[must_use]
    pub fn new(namespace: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            namespace: namespace.into(),
            name: name.into(),
        }
    }
}

impl Display for KnowledgeRecordKind {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "{}.{}", self.namespace, self.name)
    }
}

/// Exact version of one registered knowledge schema.
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct KnowledgeSchemaId {
    pub kind: KnowledgeRecordKind,
    pub version: u32,
}

impl KnowledgeSchemaId {
    #[must_use]
    pub fn new(kind: KnowledgeRecordKind, version: u32) -> Self {
        Self { kind, version }
    }
}

/// Stable holder identity shared by people and eligible institutional entities.
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum KnowledgeHolderRef {
    Person(PersonId),
    Entity(EntityRef),
}

impl KnowledgeHolderRef {
    #[must_use]
    pub const fn is_person_entity(&self) -> bool {
        matches!(self, Self::Entity(EntityRef::Person(_)))
    }
}

/// Whether a domain entity schema may receive holder-relative knowledge.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum KnowledgeHolderPolicy {
    #[default]
    Disallowed,
    Allowed,
}

/// Compile-time identity for one versioned holder-relative knowledge schema.
pub trait KnowledgeRecordType {
    type Payload;

    const NAMESPACE: &'static str;
    const NAME: &'static str;
    const SCHEMA_VERSION: u32;
}

impl DomainRecordRef {
    #[must_use]
    pub fn new(
        namespace: impl Into<String>,
        kind: impl Into<String>,
        id: impl Into<String>,
    ) -> Self {
        Self {
            kind: DomainRecordKind::new(namespace, kind),
            id: id.into(),
        }
    }
}

impl Display for DomainRecordRef {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "{}:{}", self.kind, self.id)
    }
}

/// Compile-time identity for one namespaced application-defined record kind.
///
/// The associated payload stays outside the kernel's type graph. Domain
/// packages use this trait to bind stable identities and payload codecs while
/// Canwu persists the existing schema-validated [`DomainRecordRef`] shape.
pub trait DomainRecordType {
    type Payload;
    type Class: DomainKindClass;

    const NAMESPACE: &'static str;
    const NAME: &'static str;
}

mod domain_kind_class {
    pub trait Sealed {}
}

/// Sealed type-level classification for application-defined record kinds.
pub trait DomainKindClass: domain_kind_class::Sealed {
    const IS_ENTITY: bool;
}

/// Type-level class for domain kinds whose instances are entity identities.
pub enum DomainEntityKindClass {}

impl domain_kind_class::Sealed for DomainEntityKindClass {}

impl DomainKindClass for DomainEntityKindClass {
    const IS_ENTITY: bool = true;
}

/// Type-level class for domain kinds whose instances are non-entity records.
pub enum DomainValueKindClass {}

impl domain_kind_class::Sealed for DomainValueKindClass {}

impl DomainKindClass for DomainValueKindClass {
    const IS_ENTITY: bool = false;
}

/// Marker implemented automatically for entity-class domain record types.
pub trait DomainEntityType: DomainRecordType<Class = DomainEntityKindClass> {}

impl<T: DomainRecordType<Class = DomainEntityKindClass>> DomainEntityType for T {}

/// Marker implemented automatically for non-entity domain record types.
pub trait DomainValueType: DomainRecordType<Class = DomainValueKindClass> {}

impl<T: DomainRecordType<Class = DomainValueKindClass>> DomainValueType for T {}

/// Typed façade over a stable application-defined record identity.
///
/// Its serialized representation is exactly the wrapped [`DomainRecordRef`];
/// the marker exists only at compile time.
#[derive(Serialize)]
#[serde(transparent, bound = "")]
pub struct TypedDomainRecordRef<T: DomainRecordType> {
    reference: DomainRecordRef,
    #[serde(skip)]
    marker: PhantomData<fn() -> T>,
}

impl<T: DomainRecordType> Clone for TypedDomainRecordRef<T> {
    fn clone(&self) -> Self {
        Self {
            reference: self.reference.clone(),
            marker: PhantomData,
        }
    }
}

impl<T: DomainRecordType> std::fmt::Debug for TypedDomainRecordRef<T> {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_tuple("TypedDomainRecordRef")
            .field(&self.reference)
            .finish()
    }
}

impl<T: DomainRecordType> PartialEq for TypedDomainRecordRef<T> {
    fn eq(&self, other: &Self) -> bool {
        self.reference == other.reference
    }
}

impl<T: DomainRecordType> Eq for TypedDomainRecordRef<T> {}

impl<T: DomainRecordType> PartialOrd for TypedDomainRecordRef<T> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<T: DomainRecordType> Ord for TypedDomainRecordRef<T> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.reference.cmp(&other.reference)
    }
}

impl<T: DomainRecordType> Hash for TypedDomainRecordRef<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.reference.hash(state);
    }
}

impl<'de, T: DomainRecordType> Deserialize<'de> for TypedDomainRecordRef<T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let reference = DomainRecordRef::deserialize(deserializer)?;
        Self::from_untyped(reference).map_err(|reference| {
            serde::de::Error::custom(format!(
                "domain record reference {reference} does not match typed kind {}",
                DomainRecordKind::for_type::<T>()
            ))
        })
    }
}

impl<T: DomainRecordType> TypedDomainRecordRef<T> {
    #[must_use]
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            reference: DomainRecordRef {
                kind: DomainRecordKind::for_type::<T>(),
                id: id.into(),
            },
            marker: PhantomData,
        }
    }

    #[must_use]
    pub const fn as_untyped(&self) -> &DomainRecordRef {
        &self.reference
    }

    #[must_use]
    pub fn into_untyped(self) -> DomainRecordRef {
        self.reference
    }

    /// Converts an untyped reference when its namespaced kind matches `T`.
    ///
    /// # Errors
    ///
    /// Returns the original reference when it belongs to another kind.
    pub fn from_untyped(reference: DomainRecordRef) -> Result<Self, DomainRecordRef> {
        if !reference.kind.matches_type::<T>() {
            return Err(reference);
        }
        Ok(Self {
            reference,
            marker: PhantomData,
        })
    }

    #[must_use]
    pub fn id(&self) -> &str {
        &self.reference.id
    }
}

impl<T: DomainRecordType> Display for TypedDomainRecordRef<T> {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&self.reference, formatter)
    }
}

impl<T: DomainRecordType> From<TypedDomainRecordRef<T>> for DomainRecordRef {
    fn from(reference: TypedDomainRecordRef<T>) -> Self {
        reference.into_untyped()
    }
}

impl<T: DomainEntityType> From<TypedDomainRecordRef<T>> for EntityRef {
    fn from(reference: TypedDomainRecordRef<T>) -> Self {
        Self::Domain(reference.into_untyped())
    }
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CoreEntityKind {
    Army,
    Government,
    Organization,
    Person,
    Resource,
    Route,
    Territory,
}

/// Serializable entity reference used by events, queries, and generic tools.
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(tag = "type", content = "id", rename_all = "snake_case")]
pub enum EntityRef {
    Army(ArmyId),
    Domain(DomainRecordRef),
    Government(GovernmentId),
    Organization(OrganizationId),
    Person(PersonId),
    Resource(ResourceId),
    Route(RouteId),
    Territory(TerritoryId),
}

impl Display for EntityRef {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Army(id) => write!(formatter, "army:{id}"),
            Self::Domain(reference) => write!(formatter, "domain:{reference}"),
            Self::Government(id) => write!(formatter, "government:{id}"),
            Self::Organization(id) => write!(formatter, "organization:{id}"),
            Self::Person(id) => write!(formatter, "person:{id}"),
            Self::Resource(id) => write!(formatter, "resource:{id}"),
            Self::Route(id) => write!(formatter, "route:{id}"),
            Self::Territory(id) => write!(formatter, "territory:{id}"),
        }
    }
}

impl EntityRef {
    #[must_use]
    pub const fn core_kind(&self) -> Option<CoreEntityKind> {
        match self {
            Self::Army(_) => Some(CoreEntityKind::Army),
            Self::Domain(_) => None,
            Self::Government(_) => Some(CoreEntityKind::Government),
            Self::Organization(_) => Some(CoreEntityKind::Organization),
            Self::Person(_) => Some(CoreEntityKind::Person),
            Self::Resource(_) => Some(CoreEntityKind::Resource),
            Self::Route(_) => Some(CoreEntityKind::Route),
            Self::Territory(_) => Some(CoreEntityKind::Territory),
        }
    }
}

/// One named contribution to a rule evaluation, with the evidence it read.
///
/// Term IDs and their meaning are application content. The contribution is an
/// integer in the rule's own fixed unit.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct EvaluationTerm {
    pub term_id: String,
    pub contribution: i64,
    /// Persisted evidence the term read, strictly sorted and unique.
    pub evidence: Vec<EvidenceRef>,
}

/// Explains how one application rule produced one integer result for one
/// subject at one boundary.
///
/// A trace is boundary evidence, never simulation state: nothing reads it back
/// to decide an outcome. Rule IDs, versions, and term semantics are
/// application content; the engine checks only shape, limits, subject
/// identity, and evidence availability. The result is recorded as the rule
/// computed it and need not equal the sum of the term contributions.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct EvaluationTraceRecord {
    pub rule_id: String,
    pub rule_version: String,
    pub subject: EntityRef,
    pub terms: Vec<EvaluationTerm>,
    pub result: i64,
    /// Boundary whose settlement evaluated the rule.
    pub boundary: BoundaryId,
}

/// `SplitMix64` is compact, deterministic, serializable, and sufficient for the
/// initial movement slice.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct DeterministicRng {
    state: u64,
}

impl DeterministicRng {
    const STEP: u64 = 0x9E37_79B9_7F4A_7C15;

    #[must_use]
    pub const fn from_seed(seed: u64) -> Self {
        Self { state: seed }
    }

    #[must_use]
    pub const fn state(self) -> u64 {
        self.state
    }

    #[must_use]
    pub const fn state_after(seed: u64, draws: u64) -> u64 {
        seed.wrapping_add(Self::STEP.wrapping_mul(draws))
    }

    #[must_use]
    pub const fn seed_before(state: u64, draws: u64) -> u64 {
        state.wrapping_sub(Self::STEP.wrapping_mul(draws))
    }

    pub fn next_u64(&mut self) -> u64 {
        self.state = self.state.wrapping_add(Self::STEP);
        let mut value = self.state;
        value = (value ^ (value >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
        value = (value ^ (value >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
        value ^ (value >> 31)
    }

    /// Returns a uniformly distributed value in `[0, upper_exclusive)`.
    ///
    /// Zero returns zero. Rejection sampling is used so non-power-of-two
    /// bounds do not introduce modulo bias.
    pub fn range(&mut self, upper_exclusive: u64) -> u64 {
        if upper_exclusive == 0 {
            return 0;
        }
        let rejection_threshold = upper_exclusive.wrapping_neg() % upper_exclusive;
        loop {
            let value = self.next_u64();
            if value >= rejection_threshold {
                return value % upper_exclusive;
            }
        }
    }

    /// Returns the historical modulo-reduction value for the V1 random-stream
    /// contract.
    #[must_use]
    pub fn range_modulo(&mut self, upper_exclusive: u64) -> u64 {
        if upper_exclusive == 0 {
            return 0;
        }
        self.next_u64() % upper_exclusive
    }
}

/// Error returned when a schema registration would replace an existing type.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SchemaRegistryError {
    DuplicateType(String),
}

impl Display for SchemaRegistryError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::DuplicateType(type_name) => {
                write!(formatter, "schema type {type_name} is already registered")
            }
        }
    }
}

impl std::error::Error for SchemaRegistryError {}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct FieldSchema {
    pub name: String,
    pub value_type: String,
    pub description: String,
    pub reference_type: Option<String>,
    pub writable_via_debug_command: bool,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct TypeSchema {
    pub type_name: String,
    pub description: String,
    pub fields: Vec<FieldSchema>,
}

#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct SchemaRegistry {
    types: BTreeMap<String, TypeSchema>,
}

impl SchemaRegistry {
    /// Registers a schema without replacing a different existing definition.
    ///
    /// Re-registering an identical definition is accepted for idempotent
    /// plugin registration.
    ///
    /// # Errors
    ///
    /// Returns [`SchemaRegistryError::DuplicateType`] when the type name is
    /// already registered with a different definition.
    pub fn register(&mut self, schema: TypeSchema) -> Result<(), SchemaRegistryError> {
        if let Some(existing) = self.types.get(&schema.type_name) {
            if existing == &schema {
                return Ok(());
            }
            return Err(SchemaRegistryError::DuplicateType(schema.type_name));
        }
        self.types.insert(schema.type_name.clone(), schema);
        Ok(())
    }

    #[must_use]
    pub fn get(&self, type_name: &str) -> Option<&TypeSchema> {
        self.types.get(type_name)
    }

    pub fn iter(&self) -> impl Iterator<Item = &TypeSchema> {
        self.types.values()
    }
}

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

    struct Office;

    impl DomainRecordType for Office {
        type Payload = String;
        type Class = DomainEntityKindClass;

        const NAMESPACE: &'static str = "fixture.governance";
        const NAME: &'static str = "office";
    }

    struct Obligation;

    impl DomainRecordType for Obligation {
        type Payload = String;
        type Class = DomainValueKindClass;

        const NAMESPACE: &'static str = "fixture.governance";
        const NAME: &'static str = "obligation";
    }

    struct Assessment;

    impl KnowledgeRecordType for Assessment {
        type Payload = String;

        const NAMESPACE: &'static str = "fixture.knowledge";
        const NAME: &'static str = "assessment";
        const SCHEMA_VERSION: u32 = 2;
    }

    #[test]
    fn typed_domain_identity_preserves_wire_shape_and_kind_boundary() {
        let typed = TypedDomainRecordRef::<Office>::new("secretariat");
        let raw = DomainRecordRef::new("fixture.governance", "office", "secretariat");

        assert_eq!(
            serde_json::to_value(&typed).expect("typed identity should serialize"),
            serde_json::to_value(&raw).expect("raw identity should serialize")
        );
        let round_trip: TypedDomainRecordRef<Office> = serde_json::from_value(
            serde_json::to_value(&typed).expect("typed identity should serialize"),
        )
        .expect("typed identity should deserialize");
        assert_eq!(round_trip.as_untyped(), &raw);
        assert_eq!(EntityRef::from(round_trip), EntityRef::Domain(raw.clone()));

        let wrong_kind =
            DomainRecordRef::new("fixture.governance", "obligation", "secretariat-duty");
        assert_eq!(
            TypedDomainRecordRef::<Office>::from_untyped(wrong_kind.clone()),
            Err(wrong_kind)
        );
        assert!(TypedDomainRecordRef::<Obligation>::from_untyped(raw).is_err());
        assert!(
            serde_json::from_value::<TypedDomainRecordRef<Office>>(serde_json::json!({
                "kind": {
                    "namespace": "fixture.governance",
                    "name": "obligation"
                },
                "id": "secretariat-duty"
            }))
            .is_err()
        );
    }

    #[test]
    fn knowledge_identity_and_holder_wire_shapes_are_stable() {
        let kind = KnowledgeRecordKind::new(Assessment::NAMESPACE, Assessment::NAME);
        let schema = KnowledgeSchemaId::new(kind.clone(), Assessment::SCHEMA_VERSION);

        assert_eq!(kind.to_string(), "fixture.knowledge.assessment");
        assert_eq!(schema.version, 2);
        assert_eq!(schema.kind, kind);
        assert_eq!(
            KnowledgeHolderPolicy::default(),
            KnowledgeHolderPolicy::Disallowed
        );

        assert_eq!(
            serde_json::to_value(KnowledgeHolderRef::Person(PersonId::new(7)))
                .expect("person holder should serialize"),
            serde_json::json!({ "type": "person", "value": 7 })
        );
        let invalid_shape = KnowledgeHolderRef::Entity(EntityRef::Person(PersonId::new(7)));
        assert!(invalid_shape.is_person_entity());
        let institution =
            KnowledgeHolderRef::Entity(EntityRef::Organization(OrganizationId::new(3)));
        assert!(!institution.is_person_entity());
        assert_eq!(
            serde_json::to_value(institution).expect("institution holder should serialize"),
            serde_json::json!({
                "type": "entity",
                "value": { "type": "organization", "id": 3 }
            })
        );
    }

    #[test]
    fn exact_domain_record_evidence_has_a_stable_wire_identity() {
        let evidence = EvidenceRef::DomainRecordVersion(DomainRecordVersionRef {
            record: DomainRecordRef::new("fixture.information", "dispatch", "dispatch-7"),
            version: 2,
            established_by: DomainRecordVersionSource::BoundaryChange {
                boundary: BoundaryId::new(12),
                change_index: 3,
            },
        });

        assert_eq!(
            serde_json::to_value(evidence).expect("evidence should serialize"),
            serde_json::json!({
                "type": "domain_record_version",
                "value": {
                    "record": {
                        "kind": {
                            "namespace": "fixture.information",
                            "name": "dispatch"
                        },
                        "id": "dispatch-7"
                    },
                    "version": 2,
                    "established_by": {
                        "type": "boundary_change",
                        "boundary": 12,
                        "change_index": 3
                    }
                }
            })
        );
    }

    #[test]
    fn deterministic_range_stays_bounded_for_non_power_of_two_limits() {
        for seed in 0..32 {
            let mut rng = DeterministicRng::from_seed(seed);
            assert_eq!(rng.range(0), 0);
            for _ in 0..128 {
                assert!(rng.range(7) < 7);
            }
        }
    }

    #[test]
    fn schema_registration_is_idempotent_but_rejects_definition_replacement() {
        let schema = TypeSchema {
            type_name: "fixture.office".to_owned(),
            description: "An office".to_owned(),
            fields: vec![FieldSchema {
                name: "name".to_owned(),
                value_type: "string".to_owned(),
                description: "The office name".to_owned(),
                reference_type: None,
                writable_via_debug_command: false,
            }],
        };
        let mut registry = SchemaRegistry::default();
        registry
            .register(schema.clone())
            .expect("the first schema registration should succeed");
        registry
            .register(schema.clone())
            .expect("an identical schema registration should be idempotent");

        let mut conflicting = schema;
        conflicting.description = "A different office".to_owned();
        assert_eq!(
            registry
                .register(conflicting)
                .expect_err("a different definition must not replace the registered schema"),
            SchemaRegistryError::DuplicateType("fixture.office".to_owned())
        );
    }
}