soma-som-core 0.1.0

Universal soma(som) structural primitives — Quad / Tree / Ring / Genesis / Fingerprint / TemporalLedger / CrossingRecord
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
// SPDX-License-Identifier: LGPL-3.0-only
#![allow(missing_docs)]

//! Lexicon: the ring's semantic dictionary (Layer 1 — vocabulary registry).
//!
//! Each organ implements [`LexiconProvider`] to register its domain vocabulary.
//! The ring engine collects providers at startup — same lifecycle as
//! [`ThroughRing`](crate::extension::ThroughRing) delegates.
//!
//! ## Spec traceability
//! - Layer 1: Four-layer lexicon architecture (vocabulary registry)
//! - Layer 1: vocabulary-as-topology recursion
//! - OPUS §10.3 + §A: vocabulary-as-topology — "position IS semantic role"
//!
//! ## Layer 0 → Layer 1 coordinate recursion
//!
//! Layer 0 (`crate::vocab`) binds 72 canonical terms to `(UnitId, Layer, Element)`
//! positions. Layer 1 inherits this discipline: every `LexiconEntry` carries a
//! [`VocabCoord`] anchoring it to a structural cell in its organ's unit grid.
//! World is *derivable* from `coordinate.unit`; category is *derivable* from the
//! key prefix. Neither field is stored — removing redundancy prevents architectural
//! corruption (e.g., prior state where entries carried
//! `world = WCN` instead of the correct `WAY`).
//!
//! ### Fixture example (from GUARD — guard.finding.severity.critical)
//!
//! ```rust
//! # use soma_som_core::lexicon::{LexiconEntry, VocabCoord};
//! # use soma_som_core::types::{UnitId, Layer, Element};
//! let entry = LexiconEntry {
//!     key: "guard.finding.severity.critical".into(),
//!     // (OU, Data, Root) — GUARD's security-finding structural cell.
//!     // The coordinate IS part of the term's definition, per OPUS §A.
//!     coordinate: VocabCoord { unit: UnitId::OU, layer: Layer::Data, element: Element::Root },
//!     default_en: "Critical".into(),
//!     related: vec!["guard.finding.severity.high".into()],
//!     ordinal: Some(3),
//!     invariant: false,
//! };
//! assert_eq!(entry.coordinate.unit, UnitId::OU);
//! ```

use crate::types::{Element, Layer, UnitId, World};

// ── Types ──────────────────────────────────────────────────────────────────

/// Structural coordinate anchoring a Layer 1 entry within its organ's 4×3 grid.
///
/// Reuses [`UnitId`], [`Layer`], [`Element`] from Layer 0 (`crate::types`),
/// making vocabulary-as-topology recursive from Layer 0 to Layer 1 per OPUS §10.3.
///
/// The coordinate IS part of the term's semantic definition — changing it changes
/// the architectural meaning of the term, not just its metadata.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct VocabCoord {
    /// The architectural unit this entry belongs to (determines its world).
    pub unit: UnitId,
    /// The layer within the unit's 4×3 grid (Data / Server / Client / Interface).
    pub layer: Layer,
    /// The element within the layer (Root / Pointer / Tree).
    pub element: Element,
}

impl VocabCoord {
    /// Derive the World from this coordinate's unit.
    ///
    /// World is not stored on [`LexiconEntry`] — it is fully determined by `unit`.
    pub fn world(&self) -> World {
        World::from_unit(self.unit)
    }
}

/// A semantic atom — the smallest unit of meaning an organ can express.
///
/// Each entry is anchored to a `(UnitId, Layer, Element)` structural coordinate,
/// making vocabulary-as-topology recursive from Layer 0 to Layer 1 (OPUS §10.3).
///
/// **Field discipline:**
/// - `world` is **not** stored — derivable via `coordinate.world()`.
/// - `category` is **not** stored — derivable from key prefix and coordinate.
///
/// Removing these fields prevents architectural corruption (e.g., an organ
/// mis-assigning `world = WCN` to a `WAY`-unit entry).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LexiconEntry {
    /// Dot-notation key, e.g. `"guard.finding.severity.critical"`.
    /// Must start with the organ's domain prefix.
    pub key: String,

    /// Structural coordinate — mandatory. Anchors this entry to a cell in the
    /// organ's unit grid. Must satisfy `coordinate.unit == organ's declared unit`.
    pub coordinate: VocabCoord,

    /// English default — always provided. The fallback floor.
    pub default_en: String,

    /// Related terms (semantic links within and across domains).
    pub related: Vec<String>,

    /// Ordinal position for enumeration members.
    /// e.g., severity: low=0, medium=1, high=2, critical=3.
    pub ordinal: Option<u32>,

    /// Invariant terms cannot be localized — they ARE the ontology.
    /// Invariant entries bypass collision checking (wire protocol literals).
    pub invariant: bool,
}

/// Coordinate validation error returned by [`LexiconProvider::validate_coordinates`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CoordinateError {
    /// An entry's coordinate.unit does not match the organ's declared unit.
    WrongUnit {
        /// Key of the offending entry.
        key: String,
        /// The organ's declared unit (from `primary_world()` / unit registration).
        expected: UnitId,
        /// The unit found in the entry's coordinate.
        found: UnitId,
    },
    /// Two non-invariant entries from different organs claim the same cell.
    Collision {
        /// The conflicting cell.
        coord: VocabCoord,
        /// Key of the entry in this organ that conflicts.
        key: String,
    },
}

/// Structured description for AI grounding and documentation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TermDescription {
    /// One-line summary: "The highest severity level for security findings"
    pub summary: String,

    /// Detailed explanation suitable for AI context window.
    pub explanation: String,

    /// Usage examples: how this term appears in FU.Data commands.
    pub examples: Vec<String>,

    /// Constraints: valid values, ranges, combinations.
    pub constraints: Vec<String>,
}

// ── Trait ───────────────────────────────────────────────────────────────────

/// Implemented by each organ alongside its ring extension traits.
///
/// The ring engine does NOT know about this trait at cycle time — vocabulary
/// is queried, not cycled. Providers register at startup, same lifecycle as
/// [`ThroughRing`](crate::extension::ThroughRing) delegates.
///
/// ## Layer 1 — vocabulary registry
///
/// Layer 1 (Semantic Lexicon) sits above Layer 0 (Structural Vocabulary,
/// the 72 `VocabTerm` entries in [`crate::vocab`]). Organs own their domain
/// vocabulary (Example: GUARD speaks "finding", STORE speaks "domain",
/// DIRECTOR speaks "identity"). This trait gives that knowledge a standard shape.
///
/// Each organ's `vocabulary()` entries must carry a [`VocabCoord`] with
/// `coordinate.unit == declared_unit()`. [`LexiconProvider::validate_coordinates`] enforces this
/// at organ registration time. Gate 54 enforces it statically at pre-commit.
pub trait LexiconProvider: Send + Sync {
    /// The organ's namespace prefix (e.g., `"guard"`, `"store"`, `"director"`).
    /// Must match the organ's FU.Data namespace prefix.
    fn domain(&self) -> &str;

    /// The architectural unit this organ constitutively occupies.
    ///
    /// Each organ lives in exactly one unit — this is an architectural fact.
    /// Example: DIRECTOR=FU, GUARD=OU, MIRROR=MU, STORE=CU, WALL=OU,
    /// ORCHESTRATOR=SU. Used to validate [`VocabCoord::unit`] on all entries.
    fn declared_unit(&self) -> UnitId;

    /// The interrogative world this organ constitutively occupies.
    ///
    /// Derivable from `declared_unit().world()`, but kept explicit for engine
    /// WorldRegistry building. Must equal `declared_unit().world()`.
    fn primary_world(&self) -> World;

    /// All semantic terms this organ defines.
    fn vocabulary(&self) -> Vec<LexiconEntry>;

    /// Describe a specific term (for AI grounding, help text, discovery).
    /// Returns `None` if the term is not in this organ's domain.
    fn describe(&self, key: &str) -> Option<TermDescription>;

    /// Rendering packs this organ provides (Layer 2 — medium renderings).
    ///
    /// Default: no renderings (Layer 1 only). Organs that provide localized
    /// or multi-medium content override this to return their rendering packs.
    fn renderings(&self) -> Vec<RenderingPack> {
        Vec::new()
    }

    /// Validate that all vocabulary entries carry coordinates within this organ's
    /// declared unit. Called at organ mount time; failure rejects the mount.
    ///
    /// The default implementation checks every entry's `coordinate.unit` against
    /// `declared_unit()`. Override only if an organ has a legitimate cross-unit
    /// need (application topologies may vary).
    fn validate_coordinates(&self) -> Result<(), CoordinateError> {
        let expected = self.declared_unit();
        for entry in self.vocabulary() {
            if entry.coordinate.unit != expected {
                return Err(CoordinateError::WrongUnit {
                    key: entry.key.clone(),
                    expected,
                    found: entry.coordinate.unit,
                });
            }
        }
        Ok(())
    }
}

// ── Layer 2: Medium renderings ──────────────────────────────────────

/// The six media through which a semantic term can be rendered.
///
/// Each medium serves a different consumer: web UI (Text), voice assistant
/// (Voice), generative UI (Icon/Generative), CLI (Terminal), machine exchange
/// (Structured).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Medium {
    /// Plain text — UI labels, log messages, CLI output.
    Text,
    /// SSML markup — spoken by voice interfaces.
    Voice,
    /// Semantic icon reference — icon name/URI, not the image itself.
    Icon,
    /// Prose description — for AI/generative UI composition.
    Generative,
    /// ANSI-escaped formatted output — CLI with color/formatting.
    Terminal,
    /// Machine-readable format — ring-to-ring exchange, API responses.
    Structured,
}

impl Medium {
    /// All medium variants in canonical order.
    pub const ALL: [Medium; 6] = [
        Medium::Text,
        Medium::Voice,
        Medium::Icon,
        Medium::Generative,
        Medium::Terminal,
        Medium::Structured,
    ];

    /// Parse from a case-insensitive string.
    pub fn from_str_loose(s: &str) -> Option<Medium> {
        match s.to_lowercase().as_str() {
            "text" => Some(Medium::Text),
            "voice" => Some(Medium::Voice),
            "icon" => Some(Medium::Icon),
            "generative" => Some(Medium::Generative),
            "terminal" => Some(Medium::Terminal),
            "structured" => Some(Medium::Structured),
            _ => None,
        }
    }

    /// Lowercase string representation.
    pub fn as_str(&self) -> &'static str {
        match self {
            Medium::Text => "text",
            Medium::Voice => "voice",
            Medium::Icon => "icon",
            Medium::Generative => "generative",
            Medium::Terminal => "terminal",
            Medium::Structured => "structured",
        }
    }
}

/// A rendering of a semantic term in a specific medium and locale.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rendering {
    /// The Layer 1 term key this renders (e.g., `"organ-a.term.severity.critical"`).
    pub term_key: String,
    /// The rendered form (medium-specific content).
    pub content: String,
    /// Accessibility annotation (optional, medium-dependent).
    pub accessibility: Option<String>,
}

/// A collection of renderings for a specific (scope, medium, locale) triple.
///
/// Scope is either `"system"` or `"organ:{name}"`.
/// Example: `("organ:{name}", Medium::Voice, "de")` → Voice renderings
/// for an organ's vocabulary in German.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderingPack {
    /// Scope: `"system"` or `"organ:{name}"`.
    pub scope: String,
    /// Target medium.
    pub medium: Medium,
    /// BCP 47 locale code (e.g., `"de"`, `"de-AT"`, `"en-US"`).
    pub locale: String,
    /// Renderings keyed by term key.
    entries: std::collections::BTreeMap<String, Rendering>,
}

impl RenderingPack {
    /// Create a new empty rendering pack.
    pub fn new(scope: impl Into<String>, medium: Medium, locale: impl Into<String>) -> Self {
        Self {
            scope: scope.into(),
            medium,
            locale: locale.into(),
            entries: std::collections::BTreeMap::new(),
        }
    }

    /// Insert a rendering for a term key.
    pub fn insert(&mut self, term_key: impl Into<String>, content: impl Into<String>) {
        let key = term_key.into();
        self.entries.insert(
            key.clone(),
            Rendering {
                term_key: key,
                content: content.into(),
                accessibility: None,
            },
        );
    }

    /// Insert a rendering with an accessibility annotation.
    pub fn insert_with_a11y(
        &mut self,
        term_key: impl Into<String>,
        content: impl Into<String>,
        accessibility: impl Into<String>,
    ) {
        let key = term_key.into();
        self.entries.insert(
            key.clone(),
            Rendering {
                term_key: key,
                content: content.into(),
                accessibility: Some(accessibility.into()),
            },
        );
    }

    /// Look up a rendering by term key.
    pub fn get(&self, term_key: &str) -> Option<&Rendering> {
        self.entries.get(term_key)
    }

    /// Number of renderings in this pack.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the pack is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

// ── Resolution ────────────────────────────────────────────────────────────

/// Result of resolving a term through the rendering pipeline.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedRendering {
    /// The resolved content string.
    pub content: String,
    /// Which medium was used.
    pub medium: Medium,
    /// Which locale was resolved to (may differ from requested due to fallback).
    pub locale: String,
    /// True if a rendering pack was used (false = fell back to default_en or raw key).
    pub pack_used: bool,
    /// Accessibility annotation from the rendering, if any.
    pub accessibility: Option<String>,
}

/// Resolve a term key to rendered content using the 6-step fallback chain.
///
/// Fallback chain for `(key, medium, locale)`:
/// 1. `organ:{domain}` / medium / locale (exact)
/// 2. `organ:{domain}` / medium / base-language (strip regional)
/// 3. `system` / medium / locale (exact)
/// 4. `system` / medium / base-language (strip regional)
/// 5. Layer 1 `default_en` from vocabulary
/// 6. Raw key (visible miss — never silent)
pub fn resolve_rendering(
    term_key: &str,
    medium: Medium,
    locale: &str,
    packs: &[RenderingPack],
    vocabulary: &[LexiconEntry],
) -> ResolvedRendering {
    // Check if term is invariant — bypass all rendering packs
    let vocab_entry = vocabulary.iter().find(|e| e.key == term_key);
    if let Some(entry) = vocab_entry {
        if entry.invariant {
            return ResolvedRendering {
                content: entry.default_en.clone(),
                medium,
                locale: "en".to_string(),
                pack_used: false,
                accessibility: None,
            };
        }
    }

    let domain = term_key.split('.').next().unwrap_or("");
    let organ_scope = format!("organ:{domain}");
    let base_locale = base_language(locale);

    // Steps 1-4: search packs in priority order
    let scopes_and_locales: [(&str, &str); 4] = [
        (&organ_scope, locale),           // Step 1: organ + exact locale
        (&organ_scope, &base_locale),     // Step 2: organ + base language
        ("system", locale),               // Step 3: system + exact locale
        ("system", &base_locale),         // Step 4: system + base language
    ];

    for (scope, loc) in &scopes_and_locales {
        if let Some(pack) = packs.iter().find(|p| {
            p.scope == *scope && p.medium == medium && p.locale == *loc
        }) {
            if let Some(rendering) = pack.get(term_key) {
                return ResolvedRendering {
                    content: rendering.content.clone(),
                    medium,
                    locale: pack.locale.clone(),
                    pack_used: true,
                    accessibility: rendering.accessibility.clone(),
                };
            }
        }
    }

    // Step 5: Layer 1 default_en
    if let Some(entry) = vocab_entry {
        return ResolvedRendering {
            content: entry.default_en.clone(),
            medium,
            locale: "en".to_string(),
            pack_used: false,
            accessibility: None,
        };
    }

    // Step 6: raw key (visible miss)
    ResolvedRendering {
        content: term_key.to_string(),
        medium,
        locale: locale.to_string(),
        pack_used: false,
        accessibility: None,
    }
}

/// Extract the base language from a BCP 47 locale code.
/// `"de-AT"` → `"de"`, `"en-US"` → `"en"`, `"ja"` → `"ja"`.
fn base_language(locale: &str) -> String {
    locale.split('-').next().unwrap_or(locale).to_string()
}

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

// inline: exercises module-private items via super::*
#[cfg(test)]
mod tests {
    use super::*;

    /// Minimal test provider for trait contract verification.
    struct TestProvider;

    impl LexiconProvider for TestProvider {
        fn domain(&self) -> &str {
            "test"
        }

        fn declared_unit(&self) -> UnitId {
            UnitId::FU
        }

        fn primary_world(&self) -> World {
            World::WAI
        }

        fn vocabulary(&self) -> Vec<LexiconEntry> {
            vec![LexiconEntry {
                key: "test.item.active".into(),
                coordinate: VocabCoord { unit: UnitId::FU, layer: Layer::Data, element: Element::Pointer },
                default_en: "Active".into(),
                related: vec!["test.item.inactive".into()],
                ordinal: Some(0),
                invariant: false,
            }]
        }

        fn describe(&self, key: &str) -> Option<TermDescription> {
            if key == "test.item.active" {
                Some(TermDescription {
                    summary: "An active test item".into(),
                    explanation: "Represents an item in the active state.".into(),
                    examples: vec!["test.item.active in FU.Data".into()],
                    constraints: vec!["Must be active or inactive".into()],
                })
            } else {
                None
            }
        }
    }

    #[test]
    fn lexicon_provider_is_object_safe() {
        fn _assert(_: &dyn LexiconProvider) {}
    }

    #[test]
    fn provider_domain() {
        let p = TestProvider;
        assert_eq!(p.domain(), "test");
    }

    #[test]
    fn provider_vocabulary_returns_entries() {
        let p = TestProvider;
        let vocab = p.vocabulary();
        assert_eq!(vocab.len(), 1);
        assert_eq!(vocab[0].key, "test.item.active");
        assert_eq!(vocab[0].default_en, "Active");
        assert_eq!(vocab[0].coordinate.unit, UnitId::FU);
        assert_eq!(vocab[0].coordinate.world(), World::WAI);
        assert!(!vocab[0].invariant);
        assert_eq!(vocab[0].ordinal, Some(0));
    }

    #[test]
    fn provider_describe_known_term() {
        let p = TestProvider;
        let desc = p.describe("test.item.active").unwrap();
        assert_eq!(desc.summary, "An active test item");
        assert!(!desc.explanation.is_empty());
        assert_eq!(desc.examples.len(), 1);
        assert_eq!(desc.constraints.len(), 1);
    }

    #[test]
    fn provider_describe_unknown_term_returns_none() {
        let p = TestProvider;
        assert!(p.describe("test.nonexistent").is_none());
    }

    #[test]
    fn entry_keys_must_start_with_domain_prefix() {
        let p = TestProvider;
        let domain = p.domain();
        for entry in p.vocabulary() {
            assert!(
                entry.key.starts_with(&format!("{domain}.")),
                "entry key '{}' must start with '{domain}.'",
                entry.key
            );
        }
    }

    #[test]
    fn entry_related_terms_are_dot_notation() {
        let p = TestProvider;
        for entry in p.vocabulary() {
            for related in &entry.related {
                assert!(
                    related.contains('.'),
                    "related term '{related}' should use dot notation"
                );
            }
        }
    }

    #[test]
    fn lexicon_entry_clone_and_eq() {
        let entry = LexiconEntry {
            key: "test.a".into(),
            coordinate: VocabCoord { unit: UnitId::FU, layer: Layer::Data, element: Element::Root },
            default_en: "A".into(),
            related: vec![],
            ordinal: None,
            invariant: false,
        };
        let cloned = entry.clone();
        assert_eq!(entry, cloned);
    }

    #[test]
    fn term_description_clone_and_eq() {
        let desc = TermDescription {
            summary: "s".into(),
            explanation: "e".into(),
            examples: vec!["x".into()],
            constraints: vec![],
        };
        let cloned = desc.clone();
        assert_eq!(desc, cloned);
    }

    // ── VocabCoord + validate_coordinates tests ────────────────────────────

    #[test]
    fn vocab_coord_world_derives_from_unit() {
        let coord = VocabCoord { unit: UnitId::OU, layer: Layer::Data, element: Element::Root };
        assert_eq!(coord.world(), World::WAY);

        let coord_fu = VocabCoord { unit: UnitId::FU, layer: Layer::Server, element: Element::Pointer };
        assert_eq!(coord_fu.world(), World::WAI);
    }

    #[test]
    fn vocab_coord_clone_copy_and_eq() {
        let c = VocabCoord { unit: UnitId::MU, layer: Layer::Client, element: Element::Tree };
        let d = c;
        assert_eq!(c, d);
    }

    #[test]
    fn validate_coordinates_passes_for_correct_unit() {
        let p = TestProvider;
        assert!(p.validate_coordinates().is_ok());
    }

    #[test]
    fn validate_coordinates_fails_for_wrong_unit() {
        struct WrongUnitProvider;
        impl LexiconProvider for WrongUnitProvider {
            fn domain(&self) -> &str { "wrong" }
            fn declared_unit(&self) -> UnitId { UnitId::MU }
            fn primary_world(&self) -> World { World::WIU }
            fn vocabulary(&self) -> Vec<LexiconEntry> {
                vec![LexiconEntry {
                    key: "wrong.item".into(),
                    coordinate: VocabCoord {
                        unit: UnitId::FU, // wrong — declared MU, got FU
                        layer: Layer::Data,
                        element: Element::Root,
                    },
                    default_en: "Item".into(),
                    related: vec![],
                    ordinal: None,
                    invariant: false,
                }]
            }
            fn describe(&self, _: &str) -> Option<TermDescription> { None }
        }
        let p = WrongUnitProvider;
        let err = p.validate_coordinates().unwrap_err();
        assert!(matches!(
            err,
            CoordinateError::WrongUnit { expected: UnitId::MU, found: UnitId::FU, .. }
        ));
    }

    #[test]
    fn declared_unit_matches_primary_world() {
        let p = TestProvider;
        assert_eq!(World::from_unit(p.declared_unit()), p.primary_world());
    }

    // ── Layer 2: Medium & Rendering tests ─────────────────────────────────

    #[test]
    fn medium_has_six_variants() {
        assert_eq!(Medium::ALL.len(), 6);
    }

    #[test]
    fn medium_from_str_loose_all_variants() {
        assert_eq!(Medium::from_str_loose("text"), Some(Medium::Text));
        assert_eq!(Medium::from_str_loose("voice"), Some(Medium::Voice));
        assert_eq!(Medium::from_str_loose("icon"), Some(Medium::Icon));
        assert_eq!(Medium::from_str_loose("generative"), Some(Medium::Generative));
        assert_eq!(Medium::from_str_loose("terminal"), Some(Medium::Terminal));
        assert_eq!(Medium::from_str_loose("structured"), Some(Medium::Structured));
        assert_eq!(Medium::from_str_loose("TEXT"), Some(Medium::Text));
        assert_eq!(Medium::from_str_loose("unknown"), None);
    }

    #[test]
    fn medium_as_str_round_trip() {
        for m in Medium::ALL {
            assert_eq!(Medium::from_str_loose(m.as_str()), Some(m));
        }
    }

    #[test]
    fn rendering_construction() {
        let r = Rendering {
            term_key: "organ-a.term.severity.critical".into(),
            content: "<emphasis>Kritisch</emphasis>".into(),
            accessibility: Some("Critical severity".into()),
        };
        assert_eq!(r.term_key, "organ-a.term.severity.critical");
        assert_eq!(r.content, "<emphasis>Kritisch</emphasis>");
        assert_eq!(r.accessibility.as_deref(), Some("Critical severity"));
    }

    #[test]
    fn rendering_pack_insert_and_get() {
        let mut pack = RenderingPack::new("organ:organ-a", Medium::Text, "de");
        pack.insert("organ-a.term.severity.critical", "Kritisch");
        pack.insert("organ-a.term.severity.high", "Hoch");
        pack.insert("organ-a.term.severity.low", "Niedrig");
        assert_eq!(pack.len(), 3);
        assert!(!pack.is_empty());
        let r = pack.get("organ-a.term.severity.critical").unwrap();
        assert_eq!(r.content, "Kritisch");
        assert!(pack.get("guard.nonexistent").is_none());
    }

    #[test]
    fn rendering_pack_with_accessibility() {
        let mut pack = RenderingPack::new("organ:organ-a", Medium::Icon, "en");
        pack.insert_with_a11y(
            "organ-a.term.severity.critical",
            "icon:severity-critical-red",
            "Critical severity indicator",
        );
        let r = pack.get("organ-a.term.severity.critical").unwrap();
        assert_eq!(r.content, "icon:severity-critical-red");
        assert_eq!(
            r.accessibility.as_deref(),
            Some("Critical severity indicator")
        );
    }

    #[test]
    fn rendering_pack_empty() {
        let pack = RenderingPack::new("system", Medium::Text, "en");
        assert!(pack.is_empty());
        assert_eq!(pack.len(), 0);
    }

    // ── Fallback chain tests ──────────────────────────────────────────────

    fn test_vocab() -> Vec<LexiconEntry> {
        vec![
            LexiconEntry {
                key: "organ-a.term.severity.critical".into(),
                coordinate: VocabCoord { unit: UnitId::OU, layer: Layer::Data, element: Element::Root },
                default_en: "Critical".into(),
                related: vec![],
                ordinal: Some(3),
                invariant: false,
            },
            LexiconEntry {
                key: "organ-b.unit.fu".into(),
                coordinate: VocabCoord { unit: UnitId::FU, layer: Layer::Data, element: Element::Root },
                default_en: "FU".into(),
                related: vec![],
                ordinal: None,
                invariant: true,
            },
        ]
    }

    #[test]
    fn resolve_organ_exact_locale() {
        let mut pack = RenderingPack::new("organ:organ-a", Medium::Text, "de");
        pack.insert("organ-a.term.severity.critical", "Kritisch");
        let packs = vec![pack];
        let vocab = test_vocab();

        let result = resolve_rendering(
            "organ-a.term.severity.critical",
            Medium::Text,
            "de",
            &packs,
            &vocab,
        );
        assert_eq!(result.content, "Kritisch");
        assert_eq!(result.locale, "de");
        assert!(result.pack_used);
    }

    #[test]
    fn resolve_regional_falls_back_to_base_language() {
        let mut pack = RenderingPack::new("organ:organ-a", Medium::Text, "de");
        pack.insert("organ-a.term.severity.critical", "Kritisch");
        let packs = vec![pack];
        let vocab = test_vocab();

        let result = resolve_rendering(
            "organ-a.term.severity.critical",
            Medium::Text,
            "de-AT",
            &packs,
            &vocab,
        );
        assert_eq!(result.content, "Kritisch");
        assert_eq!(result.locale, "de");
        assert!(result.pack_used);
    }

    #[test]
    fn resolve_falls_back_to_system_pack() {
        let mut sys_pack = RenderingPack::new("system", Medium::Text, "de");
        sys_pack.insert("organ-a.term.severity.critical", "Kritisch (System)");
        let packs = vec![sys_pack];
        let vocab = test_vocab();

        let result = resolve_rendering(
            "organ-a.term.severity.critical",
            Medium::Text,
            "de",
            &packs,
            &vocab,
        );
        assert_eq!(result.content, "Kritisch (System)");
        assert!(result.pack_used);
    }

    #[test]
    fn resolve_falls_back_to_default_en() {
        let packs: Vec<RenderingPack> = vec![];
        let vocab = test_vocab();

        let result = resolve_rendering(
            "organ-a.term.severity.critical",
            Medium::Text,
            "ja",
            &packs,
            &vocab,
        );
        assert_eq!(result.content, "Critical");
        assert_eq!(result.locale, "en");
        assert!(!result.pack_used);
    }

    #[test]
    fn resolve_falls_back_to_raw_key() {
        let packs: Vec<RenderingPack> = vec![];
        let vocab = test_vocab();

        let result = resolve_rendering(
            "unknown.term.here",
            Medium::Text,
            "de",
            &packs,
            &vocab,
        );
        assert_eq!(result.content, "unknown.term.here");
        assert!(!result.pack_used);
    }

    #[test]
    fn resolve_invariant_term_bypasses_packs() {
        let mut pack = RenderingPack::new("organ:organ-b", Medium::Text, "de");
        pack.insert("organ-b.unit.fu", "GE");
        let packs = vec![pack];
        let vocab = test_vocab();

        let result = resolve_rendering(
            "organ-b.unit.fu",
            Medium::Text,
            "de",
            &packs,
            &vocab,
        );
        assert_eq!(result.content, "FU");
        assert!(!result.pack_used);
    }

    #[test]
    fn resolve_voice_medium() {
        let mut pack = RenderingPack::new("organ:organ-a", Medium::Voice, "de");
        pack.insert(
            "organ-a.term.severity.critical",
            "<emphasis>Kritisch</emphasis>",
        );
        let packs = vec![pack];
        let vocab = test_vocab();

        let result = resolve_rendering(
            "organ-a.term.severity.critical",
            Medium::Voice,
            "de",
            &packs,
            &vocab,
        );
        assert_eq!(result.content, "<emphasis>Kritisch</emphasis>");
        assert_eq!(result.medium, Medium::Voice);
        assert!(result.pack_used);
    }

    #[test]
    fn resolve_organ_priority_over_system() {
        let mut organ_pack = RenderingPack::new("organ:organ-a", Medium::Text, "de");
        organ_pack.insert("organ-a.term.severity.critical", "Organ: Kritisch");
        let mut sys_pack = RenderingPack::new("system", Medium::Text, "de");
        sys_pack.insert("organ-a.term.severity.critical", "System: Kritisch");
        let packs = vec![organ_pack, sys_pack];
        let vocab = test_vocab();

        let result = resolve_rendering(
            "organ-a.term.severity.critical",
            Medium::Text,
            "de",
            &packs,
            &vocab,
        );
        assert_eq!(result.content, "Organ: Kritisch");
    }

    #[test]
    fn base_language_extraction() {
        assert_eq!(base_language("de-AT"), "de");
        assert_eq!(base_language("en-US"), "en");
        assert_eq!(base_language("ja"), "ja");
        assert_eq!(base_language("zh-Hans-CN"), "zh");
    }

    #[test]
    fn provider_default_renderings_empty() {
        let p = TestProvider;
        assert!(p.renderings().is_empty());
    }

    #[test]
    fn rendering_clone_and_eq() {
        let r = Rendering {
            term_key: "a.b".into(),
            content: "c".into(),
            accessibility: None,
        };
        assert_eq!(r, r.clone());
    }

    #[test]
    fn rendering_pack_clone_and_eq() {
        let mut pack = RenderingPack::new("system", Medium::Text, "en");
        pack.insert("a.b", "c");
        assert_eq!(pack, pack.clone());
    }

    #[test]
    fn resolved_rendering_clone_and_eq() {
        let r = ResolvedRendering {
            content: "x".into(),
            medium: Medium::Text,
            locale: "en".into(),
            pack_used: false,
            accessibility: None,
        };
        assert_eq!(r, r.clone());
    }
}